user3055201
user3055201

Reputation: 45

setting a variable in an if statement

if (x = (1+2) < 4)

Is the above snipped doable? Will it run as expected? I expect it to always set x to 3, and then run arguments if (3 < 4).

Upvotes: 0

Views: 69

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

What you want is achieved the following way

if ( ( x = 1 + 2 ) < 4 )

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

The rules of operator precedence make your condition equivalent to:

x = ((1 + 2) < 4)

So what this will really do is evaluate (1 + 2) < 4 to get true and then assign it to x.

Upvotes: 4

Related Questions