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

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

    Be very very careful.

    For fundamental types these are shortcut operators.

    But if you define these operators for your own class or enumeration types they are not shortcut. Because of this semantic difference in their usage under these different circumstances it is recommended that you do not define these operators.

    For the operator && and operator || for fundamental types the evaluation order is left to right (otherwise short cutting would be hard :-) But for overloaded operators that you define, these are basically syntactic sugar to defining a method and thus the order of evaluation of the parameters is undefined.

提交回复
热议问题