Interview question: Which one will execute faster, if (flag==0)
or if (0==flag)
? Why?
Well there is a difference when flag is a user defined type
struct sInt
{
sInt( int i ) : wrappedInt(i)
{
std::cout << "ctor called" << std::endl;
}
operator int()
{
std::cout << "operator int()" << std::endl;
return wrappedInt;
}
bool operator==(int nComp)
{
std::cout << "bool operator==(int nComp)" << std::endl;
return (nComp == wrappedInt);
}
int wrappedInt;
};
int
_tmain(int argc, _TCHAR* argv[])
{
sInt s(0);
//in this case this will probably be faster
if ( 0 == s )
{
std::cout << "equal" << std::endl;
}
if ( s == 0 )
{
std::cout << "equal" << std::endl;
}
}
In the first case (0==s) the conversion operator is called and then the returned result is compared to 0. In the second case the == operator is called.
If at all there was a difference, what stops compiler to choose the faster once? So logically, there can't be any difference. Probably this is what the interviewer expects. It is actually a brilliant question.
Well, I am agreeing completely with all said in the comments to the OP, for the exercise sake:
If the compiler is not clever enough (indeed you should not use it) or the optimization is disabled, x == 0
could compile to a native assembly jump if zero
instruction, while 0 == x
could be a more generic (and costly) comparison of numeric values.
Still, I wouldn't like to work for a boss who thinks in these terms...
Same code for amd64 with GCC 4.1.2:
.loc 1 4 0 # int f = argc;
movl -20(%rbp), %eax
movl %eax, -4(%rbp)
.loc 1 6 0 # if( f == 0 ) {
cmpl $0, -4(%rbp)
jne .L2
.loc 1 7 0 # return 0;
movl $0, -36(%rbp)
jmp .L4
.loc 1 8 0 # }
.L2:
.loc 1 10 0 # if( 0 == f ) {
cmpl $0, -4(%rbp)
jne .L5
.loc 1 11 0 # return 1;
movl $1, -36(%rbp)
jmp .L4
.loc 1 12 0 # }
.L5:
.loc 1 14 0 # return 2;
movl $2, -36(%rbp)
.L4:
movl -36(%rbp), %eax
.loc 1 15 0 # }
leave
ret
As others have said, there is no difference.
0
has to be evaluated. flag
has to be evaluated. This process takes the same time, no matter which side they're placed.
The right answer would be: they're both the same speed.
Even the expressions if(flag==0)
and if(0==flag)
have the same amount of characters! If one of them was written as if(flag== 0)
, then the compiler would have one extra space to parse, so you would have a legitimate reason at pointing out compile time.
But since there is no such thing, there is absolutely no reason why one should be faster than other. If there is a reason, then the compiler is doing some very, very strange things to generated code...
Surely no difference in terms of execution speeds. The condition needs to be evaluated in both cases in the same way.