psp1
psp1

Reputation: 537

Confused about if condition CPP

Confused about if condition, how does it executes following statements.

if(1 && (1 || 0) != 0)  or  if(1 || (1 && 0) != 0)

In above if statement what is the sequence of executing/validating the statements.
(left to right or right to left) if left to right, then if first argument/expression is true does it evaluates 2nd expression/argument? is it true for both the logical AND and OR operators.

Thanks.

Upvotes: 1

Views: 158

Answers (5)

Necrolis
Necrolis

Reputation: 26171

lets break it down step-by-step:

(1 || 0) becomes true as 1 short-circuits the expression

so (1 || 0) != 0 is true

1 && true is true by the definition of the logical && operator

or is a define/keyword for || but the first section is already true, so we short-circuit the expression again and the code inside the if block is executed.

Upvotes: 0

stch
stch

Reputation: 1

Both things are fundamentally different go read D Morgans Laws!s

Upvotes: 0

Johan Kotlinski
Johan Kotlinski

Reputation: 25739

It's left to right. || short-circuits if first expression is true, && if first expression is false.

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93030

It's left to right

  1. First executes 1. Then executes (1 || 0) != 0. To do that it executes 1 || 0 -> true, so the whole thing is true.
  2. First executes 1 - it's true, so it short circuits and returns true.

Upvotes: 1

Peter Alexander
Peter Alexander

Reputation: 54270

Logical && short circuits if the first operand evaluates to false (because false && x is false for all x)

Logical || short circuits if the first operand evaluates to true (because true || x is true for all x)

They both evaluate left-to-right.

Upvotes: 4

Related Questions