C Assignment operator puzzle
Hello…been a long time since i posted anything. Excuses apart, (most bloggers have interesting excuses..but yes it is always about – getting busy living not getting busy blogging!) here is a nice puzzle to ponder about.
The code below shows a common mistake by most beginners. For eg in this snippet:
int rateofinterest, years, amt;/*some code here*/
…if(years=6) printf(“rate of interest =5%”);
else if (years=5) printf(“rate of interest=7%”);
else printf(“invalid”);
you all know the output: it would always be rate of interest=5%. The compiler has no problem with this because a comparison operator has simply been replaced by an assignment operator. No harm done..however a similar mistake like the code below results in something weird.
int iresult, inum;scanf(“%d”,&inum);
iresult=inum%2;
if(iresult=0) printf (“even”);
else printf(“odd”);
Here, strangely the output is always “odd”. Why?





the output is “odd” because the
if(iresult=0) computes to if(0) which makes the if condition false so execution reaches the else part and “odd” is printed.
Kevin
June 2, 2007
thats precisely why compares could be written like this:
if(0=iresult)
the compiler would throw up an error when you use ‘=’ instead of ‘==’
Sharath
June 2, 2007
lol!… you guys are fast! or was it too easy?
Nirmal
June 2, 2007
way too easy:p
zakimirza
June 4, 2007