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

前端 未结 5 1117
星月不相逢
星月不相逢 2021-01-11 14:01

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

#define CONST_VALUE 5

int variable;

...

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

O         


        
5条回答
  •  梦谈多话
    2021-01-11 14:48

    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.

提交回复
热议问题