views:

871

answers:

5

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?

+1  A: 

I assume you mean stuff like a = b ? c : d, where b is the condition, c is the value when b is true, and d is the value when b is false.

FrozenFire
+3  A: 

In c++ there's no actual if part of this. It's called the ternary operator. It's used like this: <boolean statement> ? <result if true> : <result if false>; For your example above it would look like this:

C = A > B ? A : B;

This article on wikipedia also discusses it: http://en.wikipedia.org/wiki/Ternary_operation

Mykroft
+3  A: 

It works like this:

expression ? trueValue : falseValue

Which basically means that if expression evaluates to true, trueValue will be returned or executed, and falseValue will be returned or evaluated if not.

Remember that trueValue and falseValue will only be evaluated and executed if the expression is true or false, respectively. This behavior is called short circuiting.

magcius
+22  A: 

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;
lc
Furthermore, if x were a const int in your examples, the ternary version would be the only choice that compiles.
Shmoopty
Wouldn't it be better to initialize Three?
Jonathan Leffler
Shmoopty - Very true, because you can only initialize a constant when it's declared.Jonathan - Yes, yes it would. Edited. Maybe I should have done "//Three is a bool" instead.
lc
A: 

I would say the ? is a short-cut. However, some "hard-core" programmers tend to say write it out the long way so in future cases, people can easily read and modify code.

For example, if you write

int a = b<c ? b : c;

Some people claim that it's clearer to write:

if(b<c)
 a = b;
else
 a = c;

Because in future cases, people can catch it. Of course, a simple b<c ? b:c is easy to catch, but sometimes complex operations are put in and it can be hard to spot.

Daniel