+ 1

Why does this basic if-else statement refuse to post anything other than one? The integer is a=2.

#include <iostream> using namespace std; int main() { int a=2; if (a=1) { cout<<1<<endl; } else { cout<<2<<endl; } return 0; }

10th Jan 2020, 3:49 AM
Jake
7 Réponses
0
Because assignment inside an if will return true until and unless 0 is not assigned. Try assigning 0 to 'a' inside if and it should execute the else part.
10th Jan 2020, 4:15 AM
Avinesh
Avinesh - avatar
+ 2
You need to use == operator to compare variable values.... You have declared a=2 then in if condition you should specify if(a==1)
10th Jan 2020, 7:00 AM
Shobhith J B
Shobhith J B - avatar
+ 1
Output says: 1
10th Jan 2020, 3:50 AM
Jake
+ 1
You are assigning a=1 inside the if and then printing it. Why do you expect your else to be executed?
10th Jan 2020, 3:54 AM
Avinesh
Avinesh - avatar
0
Shouldn't the else statement be executed if the if statement is false?
10th Jan 2020, 3:55 AM
Jake
0
Thx. This worked. Now one other question. If you do not mind telling me the truth for the 0. Is this considerable to think there must be 0 in the first, or only "if" statement?
10th Jan 2020, 4:58 AM
Jake
0
It will be something like if(0) which returns false and the else part is executed. Sorry I meant, until and unless 0 is NOT assigned. I have changed it.
10th Jan 2020, 5:05 AM
Avinesh
Avinesh - avatar