Interview question: Which one will execute faster, if (flag==0)
or if (0==flag)
? Why?
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
{
}