Ternary conditional operator without the middle expression [duplicate]
Asked Answered
N

1

16

I realized recently that you can use the ternary operator in GCC and clang without a middle (?: or ? : works) and it will insert the first expression into the middle:

// outputs 2
cout << (2 ?: 4);
// outputs 3
cout << (0 ?  : 3);

Where is this in the standard? I looked and didn't see anything about it.

Naman answered 1/1, 2016 at 20:22 Comment(1)
It does not insert the first expression into the middle. It uses the result of the first expression in the middle. So if the first expression is a function, the function is not executed twice.Meany
R
24

It isn't in the standard at all.

What you are observing is a GCC extension: https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html

If you omit it, its value is taken from the first operand prior to contextual conversion to bool.
The extensions value lies in not repeating side-effects and reducing the source-codes size.

Riannon answered 1/1, 2016 at 20:26 Comment(5)
Thats what I thought thanks. Makes sense its present in clang then as well.Naman
Is it a good idea to have C++ code that works only with GCC/Clang ?Hollywood
@Hollywood It's a good idea to write as clean and portable code as you reasonably can without expending too much effort or unacceptably compromising your performance. In short, almost never.Riannon
In that case, you would have a non-portable, less obvious (because non-standard) code on one hand, and a little more verbose (one more bool perhaps) on the other hand. Would you choose the first option ?Hollywood
@Hollywood That small amount of extra-typing is a small price for being standards-conformant. My previous comment was a bit more general.Riannon

© 2022 - 2024 — McMap. All rights reserved.