Loops and Conditions - The trinary (?:) operator

Chapter chap5 section 10

Consider the following code which sets the variable x to the maximum of a and b.

if(a>b)
	x = a;
else
	x = b;

This looks innocent and straightforward but if the main requirement is to deliver the maximum of a and b as a value within an expression it is remarkably clumsy requiring, amongst other things, the use of an extra intermediate variable "x" to convey the result of the statement execution to the expression evaluation part of the code.

The C programming language offers an alternative via the "?:" operator. This is a trinary operator which means that three operands are associated with the operator. The syntax is

<expression1> ? <expression2> : <expression3>

The value of the expression is the value of expression2 if the value of expression1 is non-zero and the value of expression3 if the value of expression1 is zero. The setting of x to the maximum of a and b can now be achieved by the following code

x=a>b?a:b

Here is a very simple example.

main()
{
	int	a,b;
	printf("Enter 2 numbers ");
	scanf("%d%d",&a,&b);
	printf("Maximum is %d\n",a>b?a:b);
	printf("Minimum is %d\n",a>b?b:a);
}
A typical dialogue with this program, called trin, is shown below.
$ trin
Enter 2 numbers 3 5
Maximum is 5
Minimum is 3
$ trin
Enter 2 numbers 4 4
Maximum is 4
Minimum is 4
$
Another simple and useful example of the use of the trinary operator is shown by the following program.
main()
{
	int	i=0;
	while(i<3)
	{
		printf("%d error%c\n",i,i==1?' ':'s');
		i++;
	}
}
producing the output.
0 errors
1 error 
2 errors
Notice the neat way in which the final "s" is suppressed on the output.


Exercises