Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator without the middle expression

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.

like image 419
Czipperz Avatar asked Jan 01 '16 20:01

Czipperz


1 Answers

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.

like image 96
Deduplicator Avatar answered Oct 28 '22 03:10

Deduplicator