Ternary Operator CPP

Posted by: MeTh0Dz in ProgrammingComputersC on

A ternary operator is an operator that requires three different parameters/arguments. It is basically used to evaluate an if statement.

Example...

(x == 10) ? (cout << "X equals 10") : (cout << "X does not equal 10");



Basically this says, if x equals ten then print the first message, else print the second message. So it is actually the same as this...

if (x == 10) {
cout << "X equals 10";
}
else {
cout << "X does not equal 10";
}



So what happens, is the first argument is evaluated, and if it is true the next argument is executed. If the first argument is false then the third argument is executed.

Now for some more complex examples........

((x < 10) && (x > 5)) ? ((cout << "Correct") && (x = 20)) : (cout << "No");



Let's break this code down....

The first argument says, if x is less than 10 and it is greater than 5 then it is true.

The second argument says, to output "Correct" to the screen and then assign the value of 20 to x;

The third argument says to output "No" to the screen.

The new thing in this example is the '&&', which is a logical operator. This operator corresponds with the Boolean Operator 'AND'. This basically tells the compiler that you want to do both of the things contained in the argument's area. So you want to check X for being less than ten and greater than zero. Then if this evaluates to true, you want to print "Correct" to the screen and assign the value 20, to x.

A final example.....

/* Ternary Example */

#include using namespace std;

bool Hello();
int Bye();
int main() {
int x = 34;
((x < 10) && (x > 5)) ? (Hello()) : ((Bye()) && (cout << "nTernary Conditionals are Fun!"));
cout << endl << x;
return 0;
}
bool Hello() {
cout << "Hi There";
return true;
}
int Bye() {
cout << "Goodbye";
return 1;
}


This program uses bool and int type functions to perform certain functions depending on what the first argument evaluates to.

If the first argument is true, then it will run the bool type function called Hello, if it is false then it will run the int type function Bye and also print some text to the screen.

That is the basics of Ternary Operators, hopefully someone will find this helpful....

~MeTh0Dz
Trackback(0)
Comments (1)add comment

Jordan said:

Excellent blog! Is the ternary operator in C++ faster (in benchmarking) than using if/else?
 
report abuse
vote down
vote up
June 23, 2008 | url
Votes: +0

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

busy