question mark operator in expressions
Solution 1
It kind of seems like an abstract if statement.
That's correct. This is called a "ternary conditional operator".
The normal if
works on statements, while the conditional operator works on expressions.
I am wondering if there is a particular reason it seems to often be replaced by a formal if/else--besides, perhaps, readability?
There are cases where branching on statements is not enough, and you need to work on the expression level.
For instance, consider initialization:
const int foo = bar ? 5 : 3;
This could not be written using a normal if
/else
.
Anyway, people who are saying it's equivalent to the if
/else
are being imprecise. While the generated assembly is usually the same, they are not equivalent and it should not be seen as a shorthand version of if
. Simply put, use if
whenever possible, and only use the conditional operator when you need to branch on expressions.
Solution 2
?:
is the conditional operator in C.
In your example it would produce the same result as this if
statement:
if (s[i] == '-')
{
sign = -1;
}
else
{
sign = 1;
}
d0rmLife
Updated on February 11, 2020Comments
-
d0rmLife about 4 years
K&R Second Edition (page 71)-- I must have missed the explanation:
sign = (s[i] == '-') ? -1 : 1;
The context of this is a function that converts a string to a double. This part in particular comes after the function skips white space. I infer it is checking for positive or negative value, and saving it as either -1 or +1 for sign conversion at the end of the function...
return sign * val /power;
I would like to do better than infer... I'm particularly unsure of what the
?
and: 1
are doing here (or anywhere, for that matter).It kind of seems like an abstract
if
statement. Where?
checks for truth and:
iselse
... is that so? Is it limited toif/else
?I am a beginner and I haven't come across this expression syntax before, so I am wondering if there is a particular reason it seems to often be replaced by a formal
if/else
--besides, perhaps, readability? -
d0rmLife about 11 yearsChosen as answer because you addressed the why, as well as the what.