O'Reilly logo

C Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Conditional Operator: ?

C offers a shorthand way to express one form of the if else statement. It is called a conditional expression and uses the ?: conditional operator. This is a two-part operator that has three operands. Recall that operators with one operand are called unary operators and operators with two operands are called binary operators. In that tradition, operators with three operands are called ternary operators, and the conditional operator is C's only example in that category. Here is an example that yields the absolute value of a number:

x = (y < 0) ? -y : y;

Everything between the = and the semicolon is the conditional expression. The meaning of the statement is “If y is less than zero, x = -y; otherwise, x = y. In if else ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required