Dec 17, 2009 at 10:46pm UTC
Hi!
i write the following code and as an output i have "no" "yes".I wonder why i don't have "yes" "yes" instead?What is going on with zero value?
x=0;
if(x=0)
cout<<"yes";
else
cout<<"no";
x=5;
if(x=1)
cout<<"yes";
else
cout<<"no";
Dec 17, 2009 at 10:50pm UTC
Expressions in if statements are evaluated for true-/falsehood; x = 0 evaluates to false. x = 1 evaluates to true. Even if it's an assignment, the result (in x) is still evaluated.
Dec 17, 2009 at 11:57pm UTC
chris is correct, use the logical operator '==' as follows and both the expression will work as desired
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main ()
{
int x;
x=0;
if (x==0)
cout<<"yes" ;
else
cout<<"no" ;
x=5;
if (x==1)
cout<<"yes" ;
else
cout<<"no" ;
return 0;
}
Last edited on Dec 18, 2009 at 12:00am UTC
Dec 18, 2009 at 12:20am UTC
You won't get yes yes for that one. (x == 1) will evaluate to false. If, however, you used
if (x)
it would evaluate to true.
Dec 18, 2009 at 12:58am UTC
ahhh ok, i reread the original post ,,, you are right, the x=5 threw me off, i thought it was supposed to be a 'no' answer,, lol
Last edited on Dec 18, 2009 at 12:59am UTC