0

Possible Duplicates:
Output of multiple post and pre increments in one statement
Post-increment and pre-increment in 'for' loop

The following code snippet

int i=0;
printf("%d %d",i++,i++);

gives the output

1 0

I can understand that, but the following

int i=0;
printf("%d %d",++i,++i);

gives the output

2 2

Can someone explain me the second behavior?

Community
  • 1
  • 1
theReverseFlick
  • 5,894
  • 8
  • 32
  • 33
  • 1
    This is starting to smell a lot like homework, especially after your previous question: http://stackoverflow.com/questions/4706199/post-increment-and-pre-increment-in-for-loop – jason Jan 16 '11 at 16:06
  • 1
    Duplicate of: http://stackoverflow.com/questions/3812850/output-of-multiple-post-and-pre-increments-in-one-statement – Mark Loeser Jan 16 '11 at 16:07
  • Im just learning C after long time again from scratch and I get these doubts :D – theReverseFlick Jan 16 '11 at 16:13
  • 3
    Maybe the best answer to cross-reference is [Undefined behaviour and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). – Jonathan Leffler Jan 16 '11 at 16:15

3 Answers3

12

Both printfs invoke undefined-behavior. See this : Undefined behavior and sequence points

Quoted from this link:

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.

For newbies : Don't ever try to modify values of your variables twice or more in a function call argument-list. For details, click here to know what it means. :-)

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

They're both undefined behaviour. Modifying the variable i more than once is undefined. Also, C++ or C? You need to make up your mind as the behaviour of pre-increment I believe is different between them.

Puppy
  • 144,682
  • 38
  • 256
  • 465
1

You got what called 'undefined behaviour', because you are changing the same variable more than once between sequence points. Another compiler can give you different results.

a1ex07
  • 36,826
  • 12
  • 90
  • 103