Introduction to Programming and C++

Contents Previous Topic Next Topic

A very common construction in any programming language is a selection statement of the form shown in Code Fragment 1.

Code Fragment 1. Assignment based on a select statement.

	if ( condition ) {
		variable = ...;
	} else {
		variable = ...;
	}

Here, the value assigned to the variable depends on the condition. In some cases, having the entire structure of the selection statement can often obscure the actual code. For example, Code Fragment 2 selects the maximum of two values. This requires five lines of code.

Code Fragment 2. Select of the maximum.

	if ( m >= n ) {
		maxvalue = m;
	} else {
		maxvalue = n;
	}

Because such statements occur quite often, among other things, for clarity of code, it was decided to include a ternary operator, that is, an operator which takes three instead of the usual two arguments.

The format of the ternary ?: operator is

conditional statement ? true-value : false-value;

The boolean statement is evaluated and if it returns true, the second statement (between ? and :) is evaluated, otherwise, the third statement (between : and ; is evaluated.

For example, Code Fragment 2 could be rewritten as shown in Code Fragment 3.

Code Fragment 3. Select of the maximum.

	maxvalue = ( m >= n ) ? m : n;

Example 1

Whichever statement selected against by the conditional statement is not even evaluated. For example, the sinc function could be implemented as shown in Code Fragment 4.

Code Fragment 4. The sinc function.

	sincx = ( x == 0.0 ) ? 1.0 : sin(x)/x;

Clearly both sincx and x must be of type double.

Example 2

In Example 1, even if the evaluation of sin(x)/x occurred when x == 0.0, the result would have been ∞, however, if we were considering integer division, a division-by-zero would result in the halting of the program. Program 1 demonstrates how only one statement is evaluated. Perhaps 1 is not the desired result when the denominator is 0, however, this would have to be documented.

Program 1. Avoiding division-by-zero.

#include <iostream>

using namespace std;

int main() {
	int num, den;

	cout << "Enter the numerator: " << endl;
	cin >> num;
	cout << "Enter the denominator: " << endl;
	cin >> den;

	int result = ( den == 0 ) ? 1 : num/den;
	// int result = num/den;  // uncomment this to see what happens

	cout << "The result is " << result << endl;

	return 0;
}

Questions

1. Given two arrays with 10 elements each, write a for loop which stores in a third loop the maximum of the

2. Why should you never use a ternary ?: statement in a situation like:

	bool is_large = (x < -1000 || x > 1000) ? true : false;

How could you simplify this?


Contents Previous Topic Questions Next Topic