Why are multiple statements in ternary operator not executed

This question already has an answer here:

  • Undefined behavior and sequence points 4 answers
  • What's the precedence of comma operator inside conditional operator in C++? 3 answers

  • Because of operators priority. Your expression evaluates as

    ((a) ? (nb++, nb2++) : nb--), nb2--;
    

    Operator , ( comma ) is the last thing to process. And this example would not compile at all but

    The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized.

    See C++ Operator Precedence for details.


    It's expected behaviour.

    Your expression is understood by the compiler as:

    ((a) ? (nb++, nb2++) : nb--), nb2--;
    

    For more details see:

  • Something we found when using comma in condition ternary operator?
  • https://en.wikipedia.org/wiki/Comma_operator

  • use paranthesis:

    a ? (nb++, nb2++) : (nb--, nb2--);
    

    reason: lexical analysis

    链接地址: http://www.djcxy.com/p/73238.html

    上一篇: 这是C / C ++中未定义的行为(第2部分)

    下一篇: 为什么三元运算符中的多个语句没有执行