-2
#include <stdio.h>
main()
{
int a=1;
printf("%d %d %d %d %d\n",++a,a++,++a,++a,a++);
a=1;
printf("%d %d %d %d %d",a,a++,a,++a,a);
}

When I run it , it gives following output.

6 4 6 6 1
3 2 3 3 3

Please explain the code.

  • 5
    **Undefined behavior**. [Read this **carefully** if you want to know why.](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – WhozCraig Aug 18 '13 at 06:50
  • 1
    Sounds like homework. – David-SkyMesh Aug 18 '13 at 06:50
  • 1
    I am new to C language... Please explain me the code..It is not a homework... – user1521160 Aug 18 '13 at 06:53
  • 2
    @user1521160 Explanations need definition behind them. There is no definitive behavior here. The order of expression evaluation for each of those function parameter terms is *not* defined, and thus neither is the behavior. **See the first comment above.**. This code could just as easily spawn a new form of bacteria in your DVD-drive when you ran it. Thus the nature of *undefined*. – WhozCraig Aug 18 '13 at 06:55
  • 2
    As well as reading WhozCraig's link, you should probably read up on operator precedence and associativity as well - you've added them as tags, but they have nothing to do with this code. – RichieHindle Aug 18 '13 at 06:56
  • Thanks all for the help!!!Understood!!! – user1521160 Aug 18 '13 at 13:11

1 Answers1

2

The order of evaluation of function arguments is not defined, so the ++ operators could be applied in any order. You're looking at the results of undefined behaviour.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399