Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - How do I use the conditional (ternary) operator?

I've always wondered how to write the "A ? B : C" syntax in a C++ compatible language.

I think it works something like: (Pseudo code)

If A > B
   C = A
Else
   C = B

Will any veteran C++ programmer please help me out?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

It works like this:

(condition) ? true-clause : false-clause

It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example).

For example:

bool Three = SOME_VALUE;
int x = Three ? 3 : 0;

is the same as

bool Three = SOME_VALUE;
int x;
if (Three)
    x = 3;
else
    x = 0;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...