Which one will execute faster, if (flag==0) or if (0==flag)?

后端 未结 16 789
灰色年华
灰色年华 2020-11-30 17:12

Interview question: Which one will execute faster, if (flag==0) or if (0==flag)? Why?

16条回答
  •  一整个雨季
    2020-11-30 17:48

    They should be exactly the same in terms of speed.

    Notice however that some people use to put the constant on the left in equality comparisons (the so-called "Yoda conditionals") to avoid all the errors that may arise if you write = (assignment operator) instead of == (equality comparison operator); since assigning to a literal triggers a compilation error, this kind of mistake is avoided.

    if(flag=0) // <--- typo: = instead of ==; flag is now set to 0
    {
        // this is never executed
    }
    
    if(0=flag) // <--- compiler error, cannot assign value to literal
    {
    
    }
    

    On the other hand, most people find "Yoda conditionals" weird-looking and annoying, especially since the class of errors they prevent can be spotted also by using adequate compiler warnings.

    if(flag=0) // <--- warning: assignment in conditional expression
    {
    
    }
    

提交回复
热议问题