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

前端 未结 5 1075
星月不相逢
星月不相逢 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:50

    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

提交回复
热议问题