Loris Simonetti
Loris Simonetti

Reputation: 217

complex ternary operator in a while loop in c

  int a = 10;
  while (a > 8 ? (a--, (a > 7 ? a-- : a)): a--,a--) {
    printf("%d", a); // prints out 7
    break;
  }

premise: I know that the code is very badly written, this is not a real example, I will never write like that.

Can someone explain to me why it prints 7 instead of 8? it seems that the last a-- is computed, but why? the expression is true...

Upvotes: 1

Views: 76

Answers (2)

Gor Asatryan
Gor Asatryan

Reputation: 924

First step: a > 8. Check if a > 8. it is true

Second step: a--, (a > 7 ? a-- : a). Do a-- (value of a is 9). Check if a > 7. It is true, so a-- (value of a is 8)

Third step: a--. Do a-- (after coma, last operation) (value of a is 7)

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

Comma operator , has lower precedence than ternary operator ?:.

Breaking your expression up:

a > 8 // true because a = 10
  ? (
      a-- // executed, making a 9
      ,
      (
        a > 7 // true because a = 9
          ? a-- // executed, making a 8
          : a // not executed
      )
    )
  : a-- // not executed
,
a-- // executed, making a 7

Threfore a becomes 7 after evaluating the expression.

Upvotes: 6

Related Questions