What is the ? operator?

I saw this in a C++ tutorial video i'm watching but he never talks about it so what is this and what does it do, please explain in plain simple english.


This is the code that is in the video:

1
2
3
4
5
6
7
#include <iostream>
using namespace std;

template <class FIRST, class SECOND>
FIRST smaller(FIRST a, SECOND b){
    return (a<b?a:b);
}


Also, what is a:b doing?? and is "smaller" a keyword? he uses it early in the tutorial without the line of code you see and it isnt declared as a string name or any other data type name so i assume its a keyword correct?
It's a ternary operator.

Basically, it evaluates the condition on the left of it, and if it's true it takes the path to the left of the :. If false, the path to the right.

In that example, if a is less than b, it returns a. Otherwise it returns b.

It's kind of a horribly convoluted way of doing an if statement in my opinion.
The ternary operator is useful for inserting "true" or "false" for boolean values in streams. Watch out for operator precedence, though!

1
2
bool b;
cout <<( b ? "true" : "false" )<< endl;
'a:b' does nothing; ':' is not an operator. It's just the syntax of the ternary operator (also known as '?:').

Basically, it's a shorthand version of if(a<b)then(a)else(b). It's surprisingly useful from time to time.
closed account (zb0S216C)
I find them useful in constructor initialisation lists, especially.

Wazzak
That's a great example! In that context, regular if statements are not available.
Last edited on
Topic archived. No new replies allowed.