1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

A query on the output of the C program - please help

Discussion in 'C' started by deepneel25, Aug 22, 2007.

  1. deepneel25

    deepneel25 New Member

    Joined:
    Aug 22, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    #include<stdio.h>
    #include<conio.h>
    main()
    {
      int a=5;
      int b=(a)+(++a)+(++a);
       printf("%d",b);
     getch();
    }         // [COLOR=Blue]HERE THE OUTPUT COMES AS[/COLOR] [COLOR=DarkOrange]21[/COLOR]!!
    
    #include<stdio.h>
    #include<conio.h>
    main()
    {
      int a=5;
      int b=0;
      b=(a)+(++a)+(++a);
       printf("%d",b);
     getch();
    }
    
    // HERE THE OUTPUT COMES AS 19!!

    WHY THIS VARIANCE IN OUTPUT IS OCCURING?? - PLEASE HELP!!!
     
    Last edited by a moderator: Aug 22, 2007
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    Statements such as this:

    int b=(a)+(++a)+(++a);

    result in undefined behavior. Read up on sequence points.

    Also, read the "Before you make a query" thread, see the upper right corner of this page. By not using code tags, you are being rude to those you are asking for help.
     
  3. seeguna

    seeguna New Member

    Joined:
    Jun 20, 2007
    Messages:
    31
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Technical Consultant
    Location:
    Chennai
    I just run ur programs in MS Vc++6 compiler ,
    I got only 19 for both the programs.........
     
  4. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    It doesn't matter what you get; that's the point. The results are undefined. The compiler can do anything it likes. What it chooses to do is allowed to change with the next version. The standard does define the order of the additions, but it doesn't define the order of evaluating the expressions PRIOR TO the additions.

    As I said, read about sequence points. Playing with undefined operation may seem like fun but it's totally wasted time, since you can't depend upon your results being repeatable from compiler to compiler.

    Code correctness is not determined by what the compiler does; it's determined by the standards. Compiler correctness is determined by the standard. In the event the standard chooses not to define something (hardware implementations may make it infeasible to define some operations), the compiler writer may do as he wishes. And change what he does whenever he wishes.
     
    Last edited: Aug 22, 2007

Share This Page