3

Possible Duplicate:
C programming: is this undefined behavior?

#include<stdio.h>
main()
{
 int i=5;
 printf("%d%d%d",i,i++,++i);
}

my expected output is 556. But when i executed it the result is 767. how?

Community
  • 1
  • 1
san
  • 39
  • 1
  • Duplicate of [C programming: is this undefined behavior?](http://stackoverflow.com/questions/3450582/c-programming-is-this-undefined-behavior) (the code in that question is only slightly different and Jerry Coffin's answer is quite clear and concise) – James McNellis Sep 06 '10 at 17:36
  • @James That question was actually quite different: whether or not the extra argument to `printf()` resulted in "undefined behavior." This is *not* a duplicate by any means. I'll vote to reopen if this gets closed. – NullUserException Sep 06 '10 at 17:41
  • 1
    I've seen this kind of question on SO more than once. – Nyan Sep 06 '10 at 17:43
  • 1
    @NullUserException: The question was whether the code, which was quite similar to the code in this question, resulted in undefined behavior. As the top-voted answer explains, it does, because it violates the rules concerning access and modification of a variable between sequence points. I'm sure there are other questions that ask this very same thing; that was just the first one I found and it had a good answer. – James McNellis Sep 06 '10 at 17:44
  • This question was rightly closed. The same stupid question comes up every week it seems... – R.. GitHub STOP HELPING ICE Sep 06 '10 at 23:24

4 Answers4

1

You can't be sure that the increments are executed in the order you expect, because instructions inside arguments are executed in an order chosen by your compiler.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
1

You are accessing and changing a value within a sequence point (changing it twice, infact), Within a sequence point you can't be sure about the order of operations.

i.e. while you read the function call from left to right, it isn't guaranteed that the expressions are evaluated in that order. The first i might be evaluated first, yielding 5. The i++ might be evaluated first, incrementing to 6 before both ++i and i are evaluated, and so on.

nos
  • 223,662
  • 58
  • 417
  • 506
0

Interestingly Enough, the problem is that you are using the same variable more than once. If you change the code to this:

int i, j, k;
i=j=k=5;
printf("%i%i%i",i,j++,++k);

It works as expected. I think, that when you use the same variable, the order of operations gets messed up.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
-1
$ gcc -Wall arst.c  
arst.c:2:1: warning: return type defaults to ‘int’

arst.c: In function ‘main’:

arst.c:5:27: warning: operation on ‘i’ may be undefined

arst.c:5:27: warning: operation on ‘i’ may be undefined

arst.c:6:1: warning: control reaches end of non-void function

That's how.

cdmckay
  • 31,832
  • 25
  • 83
  • 114
arsenm
  • 2,903
  • 1
  • 23
  • 23