c++ problem 2

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{

int x=2;
if(x=0)
cout<<"x is 0";
else if (x=1)
cout<<"x is 1";
else if(x=2)
cout<<"x is 2 ";
else
cout<<"Other values";

return 0;
}
why x is 1 print out.
why not x is 2 print out.
= means assignment ... which you shouldn't be using here
== is the logical comparator for equality ... which you should.


x=0 actually sets x to 0
... so if (x=0) considers the value of x after this assignment. This is 0 and translates to boolean false. This if condition is not run.

x=1 sets x to 1.
... so if (x=1) considers the value of x after this assignment. This is 1 and non-zero values translate to boolean true. So it does what is in this if block.

Once it has done some if block ... it doesn't need to consider any further else if block, so it won't even look at assigning x=2.


If you want it to print "x is 2" then change all the "=" into "=="
Last edited on
thank you. i understand
Topic archived. No new replies allowed.