2

Simple question of how execution happens in C++ and Python.
If I have an if condition

if ((b == c) and (a == b))

My doubt in the above condition is,
if first part i.e. (b == c) is false
then the second condition i.e. (a == b) is executed or no matter what first part output was, second parts gets executed irrespective of that.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.