Problem with conditions

what's the difference between these two because the output isn't the same ... how is the compiler taking this ??
1
2
3
 
if ((c=1)||(c=0))   //first case
if ((c=1)&&(c=0))  //second case 

|| -> or
&& -> and

You can use 'and' 'or' 'not' as operators in c++
I bet you meant == instead of =. Though it doesn't really matter. Either way you have 1||0=1 and 1&&0=0. That's just how || and && work.
It depends on the type of c:

1) For c being int:
In a normal situation if you want to check if c has value 1 or 0 you would use the first condition. At least the first modified as @hamsterman mentioned:
if ((c==1)||(c==0)).

Second condition is totally wrong since it's always false (0). There is no way c could have 2 different values at the same time.

2) For c being bool:
Both are useless (as second in previous case) as they have fixed evaluation:
1 and 0 respectively.

let's say we have this code :
1
2
3
4
5
int c=3;
if ((c=1) || (c=0))
   cout<<"hello ";
else 
    cout <<"bye";


or this one :
1
2
3
4
if ((c=1) && (c=0))
   cout<<"hello ";
else 
    cout <<"bye";

what's the explanation of their outputs ?
Again,
it has to be

1
2
3
4
5
6
7
8
9
int c=3;
if ((c==1) || (c==0))  //c == 1 NOT c = 1
{
   cout<<"hello ";
}
else 
{
    cout <<"bye";
}


and the output would be


bye
bye


because
c = 3
doesnt fit any condition of the above.
And moreover, on the second case, it will always be "bye" as you cant have 2 values for one variable at the same time
Yea I know that is the right thing...but I have an exam and that's the type of questions that comes (complicated)
if( x ) is the same as if( x != 0 ) and
x = ... //returns ... therefor
if( x = 1 ) is the same as if( (x = 1) != 0 )
which is the same as if( 1 != 0 ) which is always true!
Topic archived. No new replies allowed.