-2
#include <stdio.h>

main()
{
  int i=5;
  printf("%d %d",i,i++);
}

Output: 6 5

Can someone please explain this kind of output? Has it something to do with the associativity of the comma operator?

user3126841
  • 155
  • 2
  • 2
  • 9
  • 1
    this [undefined behavior](http://en.wikipedia.org/wiki/Undefined_behavior) could only be explained by the specific target processor and compiler (& ABI) used. Don't rely on it. – Basile Starynkevitch Jul 17 '14 at 07:08
  • This question asked before you can look at: http://stackoverflow.com/questions/12975872/ambigious-behaviour-of-increment-operator-in-printf –  Jul 17 '14 at 07:11
  • 1
    There is no comma operator in this code. The comma is a separator between function arguments. – M.M Jul 17 '14 at 08:41

2 Answers2

1

The behaviour is unspecified. This is because the arguments to printf are not sequenced.

(Informally, you don't know when i will be incremented).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    You could elaborate your answer a little by citing the reference ;) – Theolodis Jul 17 '14 at 07:08
  • ;-) I thought it only necessary to include the supporting terms in italics. Hopefully this will stimulate the OP to investigate further. – Bathsheba Jul 17 '14 at 07:09
  • Order of argument evaluation is unspecified, not undefined. The classic undefined behaviour is to increment both args (as in the claimed duplicate) but that doesn't apply here. – Nigel Harper Jul 17 '14 at 07:48
  • @NigelHarper: You're correct. I've amended. Hopefully this answer was of some use to the OP. – Bathsheba Jul 17 '14 at 08:15
0

The order of evaluation of the arguments inside is unspecified, so depending on your C compiler and options i or i++ can get evaluated first. The output you receive is what happens when i++ gets evaluated before i.

kviiri
  • 3,282
  • 1
  • 21
  • 30
  • Or the program may crash, or delete all your files. Because it's undefined behavior. Such comments as yours may inflict the programmer to rely on compiler specific behavior and write bad programs. – JustAnotherCurious Jul 17 '14 at 07:11
  • @JustAnotherCurious, uh, having more than one argument in a function can make the program crash or delete files? Not in any C compiler, sorry. – kviiri Jul 17 '14 at 07:27
  • Having such a construction in your code makes undefined behavior. Undefined means that you can't predict what happens. This means that the program can crash. The fact that you don't know any c compiler that makes crashes in this situation doesn't mean that such compiler can't exist. – JustAnotherCurious Jul 17 '14 at 18:17
  • @JustAnotherCurious, that's not true AT ALL, see the specification. Having more than argument is perfectly fine in C. The ORDER in which the arguments are evaluated isn't specified, but that's still miles away from "your program can crash and burn your house" stuff you're presenting. Stop spreading false wisdom here. – kviiri Jul 18 '14 at 06:05