It kind of seems like an abstract if statement, where
?checks for truth and:is else... is that so?
Yeah, almost. It's called the "conditional operator" (sometimes not entirely accurately referred to as "the ternary operator", since it's the only ternary operator in C). It's not a statement though, it's an expression, it has a value. It evaluates to its second argument if the first argument evaluates to true, and to its third argument if it's false. Therefore
sign = (s[i] == '-') ? -1 : 1;
is equivalent to
if (s[i] == '-') {
sign = -1;
} else {
sign = 1;
}
Answer from user529758 on Stack OverflowIt kind of seems like an abstract if statement, where
?checks for truth and:is else... is that so?
Yeah, almost. It's called the "conditional operator" (sometimes not entirely accurately referred to as "the ternary operator", since it's the only ternary operator in C). It's not a statement though, it's an expression, it has a value. It evaluates to its second argument if the first argument evaluates to true, and to its third argument if it's false. Therefore
sign = (s[i] == '-') ? -1 : 1;
is equivalent to
if (s[i] == '-') {
sign = -1;
} else {
sign = 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.
Question mark (?) as conditional operator
What is a Question Mark “?” and Colon “:” Operator Used for?
Question mark in Boolean statement, Whats it actually doing? (Novice)
Why am I getting these strange question marks in my output?
Videos
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) { result = x; } else { result = y; } This can be rewritten as the following statement:
result = a > b ? x : y;
Can the ? operator be used this way in Elixir? I don't find anything and all the conditional statements include do-end which looks so bothersome and it's hard to believe Elixir might not support such a quick and clean way.