+ 1

Can somebody please explain how the output is 02?

int x=3; if(x=2) cout<<"0"; else cout<<"1"; cout<<x;

18th Apr 2017, 7:22 PM
Aniket Singh
5 Answers
+ 2
well in if statement you have = (assigment) so x is becoming 2, and it is true, so you have cout 0 and after that printing new value of x
18th Apr 2017, 7:26 PM
Aleksandar
Aleksandar - avatar
+ 2
yea. use x==2 instead
18th Apr 2017, 7:27 PM
Edward
+ 1
= is assignment operator or relational u have to use ==
25th Apr 2017, 4:22 AM
Mayank sahu
Mayank sahu - avatar
0
Use == (syntax variable == variable and also note that numbers count as variables) instead of =, which assigns variables to variables (relational).\ This is what you should want: int x=3; if(x==2) cout<<"0"; else cout<<"1"; cout<<x; In the original code it sets x to 2, then in the first if statement it becomes true, so it outputs 0. The else statement becomes false. Then it outputs x (which is 2). Output: 02 (in original code).
19th Apr 2018, 9:38 AM
mei
mei - avatar
- 1
Tips:You got mucked up with = and ==
28th Apr 2017, 10:44 AM
mei
mei - avatar