[ create a new paste ] login | about

Link: http://codepad.org/FJhRk5p4    [ raw code | output | fork | 4 comments ]

C, pasted on Mar 5:
1
2
3
4
5
6
7
8
#include <stdio.h>
void main() {
  int j = 0;
  int k = 0;

  printf("%d, %d\n", j, j++);
  printf("%d, %d\n", k++, k);
}


Output:
1
2
1, 0
0, 1


Create a new paste based on this one


Comments:
posted by EtFb on Mar 6
GCC on Windows (using Cygwin) gives:

1, 0
0, 0

Love that undefined evaluation order. Common Lisp FTW!
reply
posted by Rainault on Mar 6
More specifically, C does not guarantee in which order the arguments of a function will be evaluated. This means each compiler can do it differently. j++ and k++ will always return 0 because of the post-increment operation, but the other arguments will be 0 or 1 depending on whether it gets evaluated first.
reply
posted by frosch03 on Mar 6
FYI:
If you try this example in TurboC, you get:

1, 0
0, 0

as result... :)
reply
posted by glitch on Mar 15
Indeed. It's an undefined behavior.

C and C++ do not specify when the post-increment occurs within the statement, only that it is guaranteed to occur by the end token (i.e., ;) -- whether immediately before (or after) use, at the beginning (or end) of the statement, or at some point in between is not specified. For this reason, referencing a variable more than once in a statement where the post-increment operator is used results in undefined behavior. The same code may produce different results on different compilers, different architectures, or even the same compiler with different optimization settings.

So,
0, 0
0, 0
could also have been a result.

Although, for the original poster, to elaborate on the specific behavior of the initial post
1, 0
0, 1
some more, suppose we have m = 0; printf("(m++, m, m++): %d, %d, %d\n", m++, m, m++);

(m++, m, m++) gave me 1, 2, 0 (with gcc version 4.0.1 Apple Inc. build 5488), which illustrates going on with that initial post.

The post-increment operators are evaluated first and from right to left, so the "m++" in the third parameter is done first (returning 0 and incremeting m to 1). The "m++" in the first parameter is done next, since it's the next post-increment operator to do (evaluating from right to left). The first parameter returns 1 and increments m to 2. This concludes the evaluation of the post-increment operators in the statement. Now, proceeding from right to left, the rest is done. So, finally, the "m" in the second parameter is evaluated as 2 (0 incremented to 1, which was then incremented to 2).
reply