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
.