Is short-circuiting logical operators mandated? And evaluation order?

前端 未结 7 2605
广开言路
广开言路 2020-11-21 04:11

Does the ANSI standard mandate the logical operators to be short-circuited, in either C or C++?

I\'m confused for I recall the K&R book saying your code

7条回答
  •  自闭症患者
    2020-11-21 04:49

    Short circuit evaluation, and order of evaluation, is a mandated semantic standard in both C and C++.

    If it wasn't, code like this would not be a common idiom

       char* pChar = 0;
       // some actions which may or may not set pChar to something
       if ((pChar != 0) && (*pChar != '\0')) {
          // do something useful
    
       }
    

    Section 6.5.13 Logical AND operator of the C99 specification (PDF link) says

    (4). Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.

    Similarly, section 6.5.14 Logical OR operator says

    (4) Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.

    Similar wording can be found in the C++ standards, check section 5.14 in this draft copy. As checkers notes in another answer, if you override && or ||, then both operands must be evaluated as it becomes a regular function call.

提交回复
热议问题