0

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
Undefined Behavior and Sequence Points

#include<stdio.h>
int main(){
int i=5,j=5,y,x;
int m=++i;
int n=++i;
x=m+n;
y=++j + ++j ;
printf("%d  %d ",x,y);
return 0;
}

OUTPUT : 13 14 Can any one plz explain why 'y' value is 14 and not 13.

Community
  • 1
  • 1
  • You could do some debug. – Ramy Al Zuhouri Nov 17 '12 at 18:47
  • 3
    @RamyAlZuhouri debuggers are pretty unlikely to lead someone asking this question to the conclusion that it's undefined behaviour. – Flexo Nov 17 '12 at 18:48
  • If it were 13, would you ask why it's 13 and not 14? – Michael Krelin - hacker Nov 17 '12 at 18:49
  • 2
    @RamyAlZuhouri I was going to put it slightly differently from Flexo and argue that the OP had written exactly the kind of program one should write for debugging purposes when one does not know one is facing undefined behavior. He has reduced it to a minimal program that clearly shows a difference between two constructs he expected to be equivalent. How would **you** debug it? – Pascal Cuoq Nov 17 '12 at 18:50
  • 1
    Q: Why 13 14? A: `y=++j + ++j ;`: See http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – paulsm4 Nov 17 '12 at 18:50

1 Answers1

2

Most compilers will increment j twice before performing the addition and attributing the value to y, that is why the result in your case is 14.

The C standard doesn't specify the order of evaluation of that expression, though, so on another compiler the result could be 13 indeed.

In other words, this is undefined behavior and should be not be used other than in obfuscation contests and puzzles.

Daniel Scocco
  • 7,036
  • 13
  • 51
  • 78
  • “**In other words**, this is undefined behavior” You have not explained why it is undefined behavior. You have stated that the evaluation order is unspecified. That makes it unspecified behavior. The explanation of why it is undefined behavior involves sequence points, not evaluation order. – Pascal Cuoq Nov 17 '12 at 19:08
  • Because in y=++j + ++j you don't know if the ++j at right and left will be put in two separate registers? – Ramy Al Zuhouri Nov 17 '12 at 22:52