Question

int a=1,b=2,c=3;
int x=1;
int y=10;
a = x ? b : c;  
cout<< a;      // Outputs 2 (the value of b)
a = y ? b : c; 
cout<< a;      // Outputs 2 (the value of b)

Now, look at the following.

a=0;
x=0;
a = x ? b : c;
cout<< a;  //   Outputs 3 (the value of c !!!!) 

Why this unusual behaviour ?? Only when a and x are both 0, the expression evaluates to false , otherwise, always it is true. Please explain.

Was it helpful?

Solution

Because x is 0.

Recall that the ternary operator, if written condition ? a : b returns a if condition is true and b otherwise. You are using it with numbers, and any number except 0 is considered true as a boolean.

x ? b : c in your case is 0 ? 2 : 3, and since 0 is false, it evaluates to 3. That 3 then gets assigned to your a variable and printed - nothing unusual going on here.

OTHER TIPS

This looks perfectly fine. The expression a = x ? b : c is equivalent to

if (x)
    a = b;
else
    a = c;

x will evaluate to true for any nonzero value, so if you assign 0 to x prior to executing the expression, the value of c will be assigned to a, and if you assign 1 to x prior to executing the expression, the value of b will be assigned to a. The prior value of a is immaterial here.

The reason is that in C and C++ any non-zero value is evaluated as "true".

The value of 'a' only depends on the value of 'x' and 'y'. Since initially 'x' and 'y' are both greater than 0, the condition evaluates to true and you get the value of 'b' in 'a'. In the second case, 'x' is zero which evaluates the condition to false which causes 'a' to have the value of 'c'.

a = x ? b : c;

is the same as

if(x != 0) {
    a = b;
} else {
    a = c;
}

Therefore if you set x = 0 you will get a = c.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top