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

前端 未结 7 2547
广开言路
广开言路 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:51

    Yes, short-circuiting and evaluation order are required for operators || and && in both C and C++ standards.

    C++ standard says (there should be an equivalent clause in the C standard):

    1.9.18

    In the evaluation of the following expressions

    a && b
    a || b
    a ? b : c
    a , b
    

    using the built-in meaning of the operators in these expressions, there is a sequence point after the evaluation of the first expression (12).

    In C++ there is an extra trap: short-circuiting does NOT apply to types that overload operators || and &&.

    Footnote 12: The operators indicated in this paragraph are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation, and the operands form an argument list, without an implied sequence point between them.

    It is usually not recommended to overload these operators in C++ unless you have a very specific requirement. You can do it, but it may break expected behaviour in other people's code, especially if these operators are used indirectly via instantiating templates with the type overloading these operators.

提交回复
热议问题