Menu
C++ Tutorials

C++

Ternary Operator



Tutorials > C++ > Ternary Operator

View Full Source

What is a binary operator?

A binary operator is some operation operating on 2 inputs eg. 5 + 6 or 8 < 10.

What is a ternary operator?

A ternary operator is some operation operating on 3 inputs. This is so rare that there is in fact only one ternary operator in C / C++.

The ternary operator takes the form :

    logical expression ? action for true : action for false;

This may seem a little daunting but it is in fact very simple once you understand it. This statement will evaluate the logical expression and if it evaluates to true true, the entire statement will evaluate to the action for true. If the logical expression evaluates to false, the action for false is used. This is essentially the same as an if-else statement.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main()
{
	int num;
	string output;

	cout << "Please enter a number : ";
	cin >> num;

The code below shows the old method of using the if-else statement.

	if (num < 0)
		output = "Negative Number";
	else
		output = "Non-Negative Number";

The code below shows how the ternary operator can be used. Notice how the code is more compact. You may find it easier or harder to read.

num is checked to see if it is less than 0 and if it is, output is assigned the value of "Negative Number". If it is not less than 0, the other message is stored.

	output = (num < 0) ? "Negative Number" 
		: "Non-Negative Number";

	cout << output << endl;

	system("pause");

	return 0;
}

You should now have an understanding of the ternary operator. It is an extremely useful shortcut. If you feel that it is too much for you, you can stick to using the if-else statement. It is basically personal preference.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 17 - For Loop Tutorial 19 - Scope >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links