Possible Duplicate:
How do I use the conditional operator?
I’m new to C language, and in one of the sample codes I was reviewing I faced the statement:
A = A ? B: C[0]
I was just wondering what the task of the previous statement is and what will be the result after execution of the mentioned statement.
It's called a ternary operator. expr ? a : b
returns a
if expr
is true, b
if false. expr
can be a boolean expression (e.g. x > 3
), a boolean literal/variable or anything castable to a boolean (e.g. an int).
int ret = expr ? a : b
is equivalent to the following:
int ret;
if (expr) ret = a;
else ret = b;
The nice thing about the ternary operator is that it's an expression, whereas the above are statements, and you can nest expressions but not statements. So you can do things like ret = (expr ? a : b) > 0;
As an extra tidbit, Python >=2.6 has a slightly different syntax for an equivalent operation: a if expr else b
.
It assigns to A
the value of B
if A
is true, otherwise C[0]
.
?:
result = a > b ? x : y;
is identical to this block:
if (a > b) {
result = x;
}
else
{
result = y;
}
It's the same as an if else
statement.
It could be rewritten as:
if ( A != 0 )
{
A = B;
}
else
{
A = C[ 0 ];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With