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. 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 this: If y is less than zero, then x = -y; otherwise, x = y. In if else terms, the meaning can be expressed as follows:
if (y < 0) x = -y; else x = y;
This is the general form of the conditional expression:
expression1 ? expression2 : expression3
If expression1 is true (nonzero), then the whole conditional expression has ...
Get C Primer Plus®, Third 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.