C Assignment operator puzzle

Posted on June 2, 2007. Filed under: computer science, programming |

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?

Make a Comment

Make a Comment: ( 4 so far )

blockquote and a tags work here.

4 Responses to “C Assignment operator puzzle”

RSS Feed for Nirmal Thacker Comments RSS Feed

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.

thats precisely why compares could be written like this:

if(0=iresult)

the compiler would throw up an error when you use ‘=’ instead of ‘==’

lol!… you guys are fast! or was it too easy? :-)

way too easy:p


Where's The Comment Form?

  •  

    June 2007
    M T W T F S S
    « Apr   Jul »
     123
    45678910
    11121314151617
    18192021222324
    252627282930  
  • a

  • Archives

  • Blog Stats

    • 54,365 hits
  •       

    This work is licensed under a Creative Commons Attribution-No Derivative Works 3.0 Unported

    Beware however that this refers only to parts which are obviously written by me and do not have any other information about licencing. Quoted text, pictures and other content created by others is copyrighted by the corresponding authors. If you are in doubt, ask before republishing any content.

Liked it here?
Why not try sites on the blogroll...