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

前端 未结 5 1110
星月不相逢
星月不相逢 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 15:02

    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.

提交回复
热议问题