Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...