Logical Expressions in C misunderstanding

前端 未结 4 1471
不知归路
不知归路 2021-01-18 04:38

So, I was writing some code and I was getting an unexpected output in one part of my program which disrupted the entire system.

I managed to extract and simplify th

相关标签:
4条回答
  • 2021-01-18 04:57

    Operators precedence. && has higher precedence than ||.

    Your expression is the same as: ++i || (++j && k)

    ++i is TRUE, the parenthesis is not evaluated anymore.

    0 讨论(0)
  • 2021-01-18 05:04

    ++i || ++j && k is evaluate to 1 (true) because i equals 2 (++1), (++j && k) isn't evaluated because short circuit.

    0 讨论(0)
  • 2021-01-18 05:09

    From the C Standard (6.5.14 Logical OR operator)

    3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

    This expression

    ++i || ++j && k
    

    is equivalent to

    ++i || ( ++j && k )
    

    and according to the quote from the Standard the expression returns integer value 1 because ++i is not equal to zero. The subexpression ( ++j && k ) is not evaluated.

    0 讨论(0)
  • 2021-01-18 05:13

    && has higher precedence than ||. (See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B ) so

    ++i || ++j && k
    

    is

    ++i || (++j && k)
    

    and || shortcircuits if the first operator is truthy, as per 6.5.14p4 .

    If you're on gcc or clang and compile your code with -Wall, the compiler will nudge you to put those parentheses there. It's probably a good idea to heed that advice, as some people get confused by the precedences (I hear).

    0 讨论(0)
提交回复
热议问题