Both in c++ and python, and
and or
operations support short-circuiting, that is, if the left part of and
is false, the right part is not evaluated; if the left part of or
is true, the right part is not evaluated.
In c++ this is per standard (§5.14/1):
The
&&
operator groups left-to-right. The operands are both contextually converted to
bool
(Clause
4
).
The result is
true
if both operands are
true
and
false
otherwise. Unlike
&
,
&&
guarantees left-to-right
evaluation: the second operand is not evaluated if the first operand is
false
and (§5.15/1):
The
||
operator groups left-to-right. The operands are both contextually converted to
bool
(Clause
4
). It
returns
true
if either of its operands is
true
, and
false
otherwise. Unlike
|
,
||
guarantees left-to-right
evaluation; moreover, the second operand is not evaluated if the first operand evaluates to
true
.
In python that is also mentioned in the docs (python2, python3):
x or y | if x is false, then y, else x (1)
x and y | if x is false, then x, else y (2)
Notes:
(1) This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
(2) This is a short-circuit operator, so it only evaluates the second argument if the first one is True.