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 ...

Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.