black and gray laptop computer

Work Smarter with C++ and the Ternary operator

Value = Expression 1 ? Expression 2 : Expression 3

Where Expression1 evaluates to boolean, true/false.

Value will be assigned Expression 2 or Expression 3, depending on the value of Expression 1.

if Expression1 is true, Value = Expression2

if Expression1 is false, Value = Expression3

 

				
					int Value = 10 > 9 ? 100 : 200;
// Value = 100
cout << "Value=" << Value << endl;
				
			

The above example assigns 100 to Value.

Expression1 is 10>9 This evaluates to true.

Because we need Expression1 to produce a boolean value of true or false, any expression that produces a value, which itself can be converted to boolean is acceptable.

				
					int Value = 10 + 9 ? 1303 : 1200;
// Value = 1303
cout << "Value=" << Value << std::endl;
				
			

The above example works because Expression1, 10 + 9 evaluates to 19, which when converted to boolean is true (0 is false).

We don’t need to assign the resultant value to anything, or even use it.

For example, I was able to compile the following seemingly useless code:

				
					 10 > 9 ? 199 : 200;
22 < 12 ? 102 : 103;
				
			

However, when we add function calls or other functionality, we can ramp up complexity.

				
					int SecurityLevel = 1;
SecurityLevel < 10 ? cout << "Login\n" : cout << "Beat it\n";
// > Login


SecurityLevel = 10;
SecurityLevel < 10 ? cout << "Login\n" : cout << "Beat it\n";
// > Beat It
				
			

Divide By Zero

Dividing by a variable can result in a divide by zero error, which often crashes programs and CPUs.  You can test for non-zero with an IF statement, however there is an easy way to use the Ternary operator to do this for us.

				
					int y = 0;
int x = 55/y;
> DIVIDE BY ZERO
				
			

In the above example, we can see how easy it is to divide by zero when using a variable as a denominator.  Here’s an example of using the Ternary operator to keep things running smoothly.

				
					int x = 55 / ( y ? y : 1);

cout << "Divide by zero?:" << x << endl;

>Divide by zero ? : 55
				
			

Now, we have a controlled division without adding much to our code.

It’s also important to know that only two of the expressions are ever evaluated, not all three.  This is clearly seen by the example above where a divide by zero is avoided by skipping evaluation of y when it’s zero.


Lastly:

				
					cout << "3 = 3 is "
  <<
  (3 == 3
    ? "true"
    : "false"
  );
				
			

In the above example, I really mess it up by writing out the Ternary operation over several lines.  In this case, it becomes a little hard to read but shows a little more context.

Conclusion

The Ternary Operator in C++ and other languages can compact 4 lines of code into 1 single line.  In my opinion, it’s a little more difficult to read than an if/else but it saves several lines of code and is easy and flexible to use.  It’s useful to prevent divide by zero and reduce your line count.