1

Code

int main() {
  int cnt = 5;
  while(cnt > 0) {
    printf("cnt = %d %s\n", --cnt, (cnt == 0) ? "cnt == 0" : "cnt != 0"); 
  }
  return 0;
}

My Expected Output

cnt = 4 cnt != 0
cnt = 3 cnt != 0
cnt = 2 cnt != 0
cnt = 1 cnt != 0
cnt = 0 cnt == 0

Real Output

cnt = 4 cnt != 0
cnt = 3 cnt != 0
cnt = 2 cnt != 0
cnt = 1 cnt != 0
cnt = 0 cnt != 0

I think when cnt = 1 after --cnt, cnt will have new value 0, and the test cnt == 0 will be true, but the real result isn't what I expect, why?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Sagi
  • 329
  • 1
  • 4
  • 13
  • I'm fairly certain this is UB.. move the `--cnt` up above to a *statement by itself*. – user2864740 May 16 '14 at 05:59
  • I am not sure if this is UB. The order of evaluation of function parameters is unspecified by the standard. In this case, the last parameter of `printf` is evaluated before the preceding one. However, all expressions are evaluated to well defined results. – Marian May 16 '14 at 14:38
  • @Marian: Suppose you had instead `M(--p, p == q ? x : y)` where `p` and `q` are pointers; is it now the case that all expressions have well-defined results? – Eric Lippert May 16 '14 at 16:14

0 Answers0