Assigning value and compare at the same time?

1
2
int y = 1;
int x = y == functionThatReturnsOneOrTwo();


What does above code do? How do I use 'x' in if and while statement?

1
2
3
4
5
if(x){
}

while(x){
}
Last edited on
The line is treated like this:
 
int x = (y == functionThatReturnsOneOrTwo());

First it compares y to the return value of the function which results in a bool value, true or false.

Next, x is initialized using that bool value. x is an integer so the bool has to be converted to an int. true becomes 1, false becomes 0.

It looks like it makes more sense for x to be a bool, but you can use an int the same way. When you use the integer variable x as a condition to if and loops 0 will be treated as false and all other values as true.
Last edited on
y = 1 -> y is true
y == functionThsat...() -> functionThat...() is true ?
int x = (y== func() ) -> takes that

if(x) or while(x) , etc. will works if x != 0 .

but next time simply do

1
2
3
4
5
6
if(functionThatReturnsSomething())
{
}
else
{
}
Topic archived. No new replies allowed.