Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there any difference between writing

int i = 10;
if(i==10)
{
}

or 

if(10==i)
{
}


I read somewhere that in one way compiling is faster.

Thanks in advance.
Posted
Updated 16-Dec-10 21:29pm
v2

There is no functional difference, both will give the same comparison result.

As for compiling speed, that would depend on the way the compiler was coded. Modern compilers are generally smart enough to recognise the statements are functionally identical and treat them the same.
 
Share this answer
 
Comments
ShilpiP 17-Dec-10 3:39am    
What if compiler are not modern than which statement execute faster??
[no name] 17-Dec-10 3:44am    
If the compiler doesn't recognise the statements as functionally identical and compiling speed is different, it depends on the implementation of the compiler. There is no general answer to say which is faster.
Dalek Dave 17-Dec-10 3:56am    
Good answer.
Abhinav S 19-Dec-10 4:52am    
Good answer.
There should be no difference. The only thing that is handy if you always use:
if(10==i)

might be, that it will give you a compile time error when you mistakingly write:
if(10=i)
 
Share this answer
 
If the types are identical it will not make a difference (between 10==i and i==10) since the same operator== will be called and the optimizer should chose the most efficient comparison. The only question is whether your compiler treats the constant 10 as a int, long, size_t, etc...

As far as

if (int i==10) {
}

versus
int i=10;
if (10==i) {
}

The former should be preferred.
 
Share this answer
 
v2
Comments
Abhinav S 19-Dec-10 4:52am    
Added code tags.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900