开发者

What is the difference between if(CONST==variable) or if(variable==CONST)?

Is there a difference in the order of the comparison operator?

#define CONST_VALUE 5

int variable;

...

if ( variable == CONST_VALUE )   // Method 1
...

OR

if ( CONST_VALUE == variable )   // Method 2
...
开发者_如何学JAVA

Is this simply a matter of preference or is there a compelling reason for a particular comparison order?


The reason some people use method 2 is because you'll get a compiler error if you mistype a = in place of the ==.

However, you'll have people (like me) who will still use method 1 because they find it more readable and if there is an error, it will be detected during testing (or, in some cases, static analysis of the code).


The only difference is that ( CONST_VALUE == variable ) makes the common typo ( CONST_VALUE = variable ) impossible to compile.

By comparison, if ( variable = CONST_VALUE ) will result in the compiler thinking you meant to assign CONST_VALUE to 'variable'.

The =/== confusion is a pretty common source of bugs in C, which is why people are trying to work around the issue with coding conventions.

Of course, this won't save you if you're comparing two variables.

And the question seems to be a duplicate of How to check for equals? (0 == i) or (i == 0)

And here's some more information: http://cwe.mitre.org/data/definitions/481.html


As others mentioned, CONST_VALUE == variable avoids the = typo.

I still do "variable == CONST_VALUE", because I think its more readable and when I see something like:

if(false == somevariable)

my bloodpressure goes up.


The first variant

if (variable == CONST_VALUE) 

is better, because it is more readable. It follows the convention (also used in mathematics) that the value that changes most comes first.

The second variant

if (CONST_VALUE == variable)

is used by some people to prevent a mixup of equality checking with the assignment

if (CONST_VALUE = variable)

There are better ways to achieve that, for example enabling and taking heed of compiler warnings.


Others already pointed out the reason. = / == confusion. I prefer the first version because it follows the thought process more closely. Some compiler alleviate the confusion of = and == by giving a warning when it encounters something like

if(a=b)

in this case if you really wanted to do the assignation you're forced to write

if((a=b)) 

which I would write then as

if( (a=b) != 0) 

to avoid the confusion.

This said, we had in our code 1 case where we had a =/== confusion and writing it the other way round wouldn't not have aided as it was a comparison between vars.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜