+ 2

Question on If condition, How this works

int a=7,b=1; Question 1: Value of a is 8 Question 2: Value of a is 1 Question 1: if(a=8) cout<< a; Question 2: if(a=8 || b==5) cout<< a<<b;

18th Nov 2020, 2:30 PM
shrijith
shrijith - avatar
1 Respuesta
+ 4
The single '=' means assignment not comparison. The If statement expects a boolean value. for question 1 the if statement after assignment becomes if(a) cout<<a; since a is not 0 or NULL it will be evaluated as true and the if statement executes and 8 is printed out ( since a is assigned 8 ) for question 2 after assignment the if statement becomes if(a || b==5) cout<<a<<b; here again since a is not 0 or NULL the statement becomes true. Note that the second condition b==5 is not checked since the first condition is true ( in an OR statement if the first condition is true, the second condition is skipped) If you want the correct comparison use '==' instead of '='
18th Nov 2020, 2:48 PM
Ben Meehan
Ben Meehan - avatar