Ryan Peschel
Ryan Peschel

Reputation: 11996

Are these two if statements the same?

1)

if (((w || x) || y) || z)

2)

if (w || x || y || z)

I see the first one in a lot of code I'm working on and I'm wondering if I can simplify it to the second one.

Upvotes: 2

Views: 92

Answers (2)

John Kugelman
John Kugelman

Reputation: 361575

Yes, the two statements are equivalent.

7.2.1 Operator precedence and associativity

When an operand occurs between two operators with the same precedence, the associativity of the operators controls the order in which the operations are performed:

  • Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.

Upvotes: 7

SuperTron
SuperTron

Reputation: 4233

in short, in the first statement, you are checking if any of w,x,y, or z are true. Therefore, the second statement is in fact equivalent to the first.

Upvotes: 0

Related Questions