Reputation: 292
I have a book that teaches C++ programming. In the book, it says "Conditional expressions can appear in some program locations where if…else statements cannot" The book doesn't specify where. I was curious if someone can show me an example where you explicitly MUST use conditional statement and not if...else statement.
Thanks,
Upvotes: 2
Views: 137
Reputation: 15278
In general, where language expects an expression. There are several cases where ?:
operator cannot be easily replaced with if
statement. It rarely occurs in practice, but it is possible. For example:
const int x = (a > 0) ? a : 0; // (global) const/constexpr initialization
struct D: public B {
D(int a)
: B(a > 0 ? a : 0) // member initializer list
{ }
};
template<int x> struct A {
};
A<(a>0) ? a : 0> var; // template argument
Upvotes: 5
Reputation: 869
You can use the ternary operator in an expression, not just on statements. For example,
bool foo;
if (bar)
foo = false;
else
foo = true;
can be shortened to
bool foo = (bar)?false:true;
It's never necessary to perform an action, and just exists for convenience.
Upvotes: 0
Reputation: 1
'to initialize a constant variable depending on some expression' - says https://stackoverflow.com/a/3565387/3969164
Upvotes: 0
Reputation: 282026
A conditional expression is an expression, whereas an if-else is a statement. That means you can embed conditional expressions in other expressions, but you can't do that with if-else:
// works
x = flag ? 5 : 6;
// meaningless nonsense
x = if (flag) 5 else 6;
You can always rewrite the code to use if-else, but it requires restructuring the logic a bit.
Upvotes: 1