2

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,

chris
  • 2,541
  • 1
  • 23
  • 40
Grendizer
  • 292
  • 1
  • 3
  • 10
  • 1
    Inside other expressions, for example, there cannot be an if statement (since you can't nest a statement inside an expression). Using it is never a "must", though -- every form that can be realized with the conditional expresson can be re-written with equivalently behaving code using `if` statements. – The Paramagnetic Croissant Aug 26 '14 at 22:11

4 Answers4

5

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
zch
  • 14,931
  • 2
  • 41
  • 49
1

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

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.

0

'to initialize a constant variable depending on some expression' - says https://stackoverflow.com/a/3565387/3969164

Community
  • 1
  • 1