473,386 Members | 1,793 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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 2357
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.telefonica-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.com> wrote in message
news:41***************@networld.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*********@mvps.org> wrote in message
news:%2***************@TK2MSFTNGP10.phx.gbl...
"J. Jones" <jj@networld.com> wrote in message
news:41***************@networld.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
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:OW**************@tk2msftngp13.phx.gbl...
I thoroughly disagree, especially when you are working with error codes

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


I'm not sure what you are getting at here. Re-writing that without the
assignment in the if() gives us:

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

Which should generate precisely the same object code as your version.
That is not the case with the while() code I presented before. There, the
version with the assignment inside the while() is more efficient (space-wise
at least; it should be a wash speed-wide) then the version without the
assignment.

One could argue one is stylistically better than the other, but
programming style wasn't even on the radar when C was created. Writing the
smallest, fastest code in 1970s era machine was the only concern.
C languages are expression based, if takes an expression. Assignment

cannot be changed into a >> non-expression without removing the
functionality of while and a number of other things.

Yes, but you're looking at it from the wrong way. Assignment is an
expression, because they wanted to do assignments inside a while() (to make
writing a C program easier), and wanted to use the same expressions
evaluator for while statement as elsewhere (to make writing a C compiler
easier).

--
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 #11
Daniel O'Connell [C# MVP] wrote:
"James Curran" <Ja*********@mvps.org> wrote in message
news:%2***************@TK2MSFTNGP10.phx.gbl...
"J. Jones" <jj@networld.com> wrote in message
news:41***************@networld.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.


I didn't say no assignments in an if/while/whatever, just no (what I'm calling)
_RAW_ assignments meaning that if you are doing an assignment in a conditional,
stick it in parentheses:

if ((x = getvalue()) == 0) // compiles

if (x = getvalue()) // doesn't compile: no assignment in conditional

if (x = getvalue() == 0) // doesn't compile: no assignment in conditional

if ((x = getvalue())) // doesn't compile: assignment w/o conditional test

if (x == 0) // compiles

same applies to while()

This way, you get _meaningful_ error messages, don't have to play the
reverse-the-order-of-operands-in-an-if-conditional game, and all existing code
will either already comply or easily be converted to the new syntax.

Remember, this thread is about _why_ some switch the compare operands in an if,
such as if (true == x), which is bass-ackwards with respect to the way that we
verbally describe the condition.


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 #12

"J. Jones" <jj@networld.com> wrote in message
news:eh**************@TK2MSFTNGP09.phx.gbl...
Daniel O'Connell [C# MVP] wrote:
"James Curran" <Ja*********@mvps.org> wrote in message
news:%2***************@TK2MSFTNGP10.phx.gbl...
"J. Jones" <jj@networld.com> wrote in message
news:41***************@networld.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.


I didn't say no assignments in an if/while/whatever, just no (what I'm
calling) _RAW_ assignments meaning that if you are doing an assignment in
a conditional, stick it in parentheses:

if ((x = getvalue())) // doesn't compile: assignment w/o conditional test


Why must if have a conditional? What if getvalue and x are booleans? Must if
(x == true) be used as well? It doesn't even solve the entire problem, it
just solves the conditional in if problem(as I mentioned, this identical
problem can occur anywhere, even in method parameters or while).

To my mind, forcing a conditional to be combined with an assignment is
almost certainly the wrong thing to do. It complicates the language without
offering a significant enough boost in productivity or usability(usability
will actually drop, I think, producitivy could lose a little as well).

As it stands, in C#, there is only a very small circumstance where this can
happen, that is with booleans. The compiler could stand to dump out
warnings, but disallowing it in the language would be a horrid waste.
Consistency should rule over everything but the most egregious of potential
errors, and this is not one of them(the switch statement wasn't either, but
they got this one right atleast).

This is not language failure, its compiler implementation failure(failing to
issue a proper warning) or programmer failure. A programmer should be quite
capable of writing the correct statement(really, how often do you mess this
one up?).
Nov 16 '05 #13
Daniel O'Connell [C# MVP] wrote:
<snip>
This is not language failure, its compiler implementation failure(failing to
issue a proper warning) or programmer failure. A programmer should be quite
capable of writing the correct statement(really, how often do you mess this
one up?).


Never, right?

The question should be: how many times have I messed it up and _don't_ know
about it.
Nov 16 '05 #14

"J. Jones" <jj@networld.com> wrote in message
news:eB**************@TK2MSFTNGP11.phx.gbl...
Daniel O'Connell [C# MVP] wrote:
<snip>
This is not language failure, its compiler implementation failure(failing
to issue a proper warning) or programmer failure. A programmer should be
quite capable of writing the correct statement(really, how often do you
mess this one up?).


Never, right?

The question should be: how many times have I messed it up and _don't_
know about it.


Since the language barely allows it, it doesn't happen daily, or even
monthly.

However, I (and others) cover my code pretty well, and someone has certainly
caught the this mistake. I've done it, I'll admit. However, I find that only
a tiny portion of my mistakes with this particular error occurs in if
statements. I see it as commonly in while statements and in general code
where I was simply comparing two objects. Changing the semantics of if
wouldn't help any of that, my code would still be wrong and my language less
flexible.

As I said, the only foolproof way to do this is to change the langauge to
more a statement based one, or change the assignment and equality operators
to be different, := and == comes to mind.
Nov 16 '05 #15

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

Similar topics

10
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...
1
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...
21
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 :...
7
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. ...
6
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...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.