473,809 Members | 2,710 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

if comparison: value first

I see in some code, I don´t remember now if it is c# or c++, that the
when they perform a comparison they use the value first and then the
variable, like:

if( null == variable ){}

Is there an explanation for this or is it the same as doing the usual
variable == value?
--
Santi
www.syltek.com
Nov 16 '05 #1
14 2406
Is there an explanation for this or is it the same as doing the usual
variable == value?


In C++ people use it to avoid writing

if ( variable = value )

by mistake. That's perfectly valid C++ code (though modern compilers
generate a warning) where you get an assignment to variable instead of
a comparison.

Since you can't make that mistake in C#, it doesn't matter which order
you write things in.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2
Hi Santi,

It is the same as doing (variable == value). No reason for doing it other
than company policy I suppose. I certainly find it harder to read than
the regular variable == value, and value == variable is rarely found in
any code.

--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #3

"Santi" <sa****@nospam. es> wrote in message
news:cr******** **@nsnmrro2-gest.nuria.tele fonica-data.net...
I see in some code, I don´t remember now if it is c# or c++, that the
when they perform a comparison they use the value first and then the
variable, like:

if( null == variable ){}

Is there an explanation for this or is it the same as doing the usual
variable == value?


The end result is the same, however there is a reason.

In C++, if statements operated on numbers(0 being false and not-zero being
true, most of the time), therefore it was possible to accidentally do

if (variable = 5)
{
}

and have that if statement to always evaluate to true. Doing 5 = variable
causes the compiler to complain that you cannot assign to a value, thus
catching that error and avoiding a bug.

Its less important in C#, as you can only cause this error with boolean
types themselves.
Nov 16 '05 #4
> In C++ people use it to avoid writing

if ( variable = value )

by mistake. That's perfectly valid C++ code (though modern compilers
generate a warning) where you get an assignment to variable instead of
a comparison.

Since you can't make that mistake in C#, it doesn't matter which order
you write things in.


No. It still works with boolean types. Something like

if (bFlag = true)

is valid C# code and doesn't even generate a warning if true is replace with
a non-constant expression.
Nov 16 '05 #5
cody wrote:
In C++ people use it to avoid writing

if ( variable = value )

by mistake. That's perfectly valid C++ code (though modern compilers
generate a warning) where you get an assignment to variable instead
of a comparison.

Since you can't make that mistake in C#, it doesn't matter which
order you write things in.


No. It still works with boolean types. Something like

if (bFlag = true)

is valid C# code and doesn't even generate a warning if true is
replace with a non-constant expression.


so use:
if (bFlag) ...

or (instead of "if (bFlag == false)"):
if (! bFlag) ...

Hans Kesting
Nov 16 '05 #6
Santi wrote:

I see in some code, I don´t remember now if it is c# or c++, that the
when they perform a comparison they use the value first and then the
variable, like:

if( null == variable ){}

Is there an explanation for this or is it the same as doing the usual
variable == value?
--
Santi
www.syltek.com


A lot of C-based languages allow variable assignment in an if statement (one =
instead of two), which is a failure of the language. So, the idea is if you
swap the order of the operands, you will get a compiler warning if you swap the
order of the operands. In this case if you forget one =, then you will get a
compiler warning *if* you were intending to compare to a _constant_. Then
entire premise breaks down if you are intending on comparing two variables.

As I said, it is a complete failure of the language. A language should _not_
permit raw unadorned assignments within the conditional. What should be in
place is that assignments, when necessary, would have to be performed
parenthetically , such as:

if ((variable = null) == null)

and
if (variable = null) // compiler error, assignment in conditional

Then it becomes instantly obvious by looking at the code what is intended, and
the assignment in conditional warning mystery goes away.
Nov 16 '05 #7
"J. Jones" <jj@networld.co m> wrote in message
news:41******** *******@networl d.com...
A lot of C-based languages allow variable assignment in an if statement (one = instead of two), which is a failure of the language.


For if()s I'll agree. But for while() statements, it's a very useful
and valuable construct. It allows you to write things like:

while ( (x=getvalue()) != 0)
{
// do stuff
}

instead of the more clumsy:

x = getvalue()
while(x !=0)
{
// do stuff
x = getvalue();
}

as you would have in every other high level language. I'd suggest that this
was one of the main reasons for C's early popularity.

--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

Nov 16 '05 #8

"James Curran" <Ja*********@mv ps.org> wrote in message
news:%2******** *******@TK2MSFT NGP10.phx.gbl.. .
"J. Jones" <jj@networld.co m> wrote in message
news:41******** *******@networl d.com...
A lot of C-based languages allow variable assignment in an if statement

(one =
instead of two), which is a failure of the language.


For if()s I'll agree. But for while() statements, it's a very useful
and valuable construct. It allows you to write things like:


I throughly disagree, especially when you are working with error codes

T x;
if ((x = getvalue()) == 0)
{
print("ERROR!") ;
}

with pretty much the same argument you had for while, the other method is as
bad in some peoples eyes as this is to others.

Also, from a pure design standpoint, modifying if to not support assignments
is simply not going to happen. C languages are expression based, if takes an
expression. Assignment cannot be changed into a non-expression withough
removing the functionality of while and a number of other things.

Also, changing if alone would not do any good, it would simply save things
in one particular cirucmstance.

consider that

if ( 1 == (y = (( x =10) + 5 )))
{
}

and
if (1 == (y == ((x = 10) + 5)))
{

}
or

bool b = v = true;
and
bool b = v == true;

exhibits the same mistake, even though the error occurs within a grouped
expression, it is still a logic error with the same root cause...someone
used the wrong operator.

Another cute one is that disallowing assingments removes the capacity to do

if (x == y = 5)
{

}

without extraneous which, again, is a completely valid expression.
Illadvised, perhaps, but valid and consistent.

The only real way to fix this is to change the assignment or comparison
operator so that they are not so similar or to throw expression based
semantics totally out the window. I imagine that both would be unattractive
to most people who use C based languages, as that would cost us our beloved
++ and -- operators.
Nov 16 '05 #9
>> if (bFlag = true)

is valid C# code and doesn't even generate a warning if true is
replace with a non-constant expression.


so use:
if (bFlag) ...

or (instead of "if (bFlag == false)"):
if (! bFlag) ...


In expressions like

if (GetThingy() || !(GetValue() && MyValue))

The bang symbol is most likely to be overlooked thats why most times I don't
use it .
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
7263
by: chandra.somesh | last post by:
Hi I recently had to write a small code in a competition ,but my code was rejected cause it failed in 1 of test cases. The problm was .....we are given vector of strings....each string consists of either 1 or 2("12122" 0r "2121" so on..)...i had to find the that string where percentage of '1' is minimum.Now the problem and solution both are trivial but i was told that comparing double with < or > sign doesn't ensure a correct...
1
5120
by: Thats Me | last post by:
TMALSS: Task With maintenance of Access Database I did not develop, don't ask about non-commented code problems or where data dictionary is (LOL). Have table with Inventory data for all Publications held, contains binder number on shelf and is text data in numeric/alpha form i.e.; 123, 1234, 123a, 1234c. I want to stuff the last character of into a new column if it is alpha. In addition, will later
21
2056
by: tshad | last post by:
I tried to do this: public static void GetValueFromDbObject(object dbObjectValue, ref decimal destination) { destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue : (decimal)dbObjectValue; } Where I am just trying to say if dbObjectValue is either equal to a
7
13545
by: bcutting | last post by:
I am looking for a way to take a large number of images and find matches among them. These images may not be exact replicas. Images may have been resized, cropped, faded, color corrected, etc. Approach 1 Programmatically extract the information (such as Eigen Vectors/Eigen Spaces) and store them in a database. Then apply a comparison algorithm between the database entries to find like images. Approach 2
6
9875
by: Evyn | last post by:
Hi, How do I compare 2 maps for identical keys, and if they have identical keys, check if they have identical values? In either case I want to copy ONLY that key value pair to one of two different maps. I know how to copy the entire map to another: // Copy fset1 to fset3 std::copy(fset1.begin(),fset1.end(),std::inserter(fset3, fset3.begin()));
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10640
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7662
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5689
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.