Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   A query on the output of the C program - please help (http://www.go4expert.com/forums/query-output-c-program-help-t5975/)

deepneel25 22Aug2007 10:13

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

#include<stdio.h>
#include<conio.h>
main()
{
  int a=5;
  int b=(a)+(++a)+(++a);
  printf("%d",b);
 getch();
}        // HERE THE OUTPUT COMES AS 21!!

#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!!!

DaWei 22Aug2007 10:50

Re: A query on the output of the C program - please help
 
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.

seeguna 22Aug2007 11:30

Re: A query on the output of the C program - please help
 
I just run ur programs in MS Vc++6 compiler ,
I got only 19 for both the programs.........

DaWei 22Aug2007 12:00

Re: A query on the output of the C program - please help
 
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.


All times are GMT +5.5. The time now is 13:42.