Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const
correctness in a compact way.
Something like this:
const int n = (x != 0) ? 10 : 20;
so basically n
is a const
whose initial value is dependent on a condition statement. The easiest alternative is to make n
not a const
, this would allow an ordinary if
to initialize it. But if you want it to be const
, it cannot be done with an ordinary if
. The best substitute you could make would be to use a helper function like this:
int f(int x) {
if(x != 0) { return 10; } else { return 20; }
}
const int n = f(x);
but the ternary if version is far more compact and arguably more readable.