Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP C/HP-UX Reference Manual: Workstations and Servers > Chapter 5 Expressions

Conditional Operator

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

 » Index

The conditional operator (?:) performs an if-then-else using three expressions.

Syntax

conditional-expression ::=
logical-OR-expression
logical-OR-expression ? expression : conditional-expression

Description

A conditional expression consists of three expressions. The first and the second expressions are separated with a ? character; the second and third expressions are separated with a : character.

The first expression is evaluated. If the result is nonzero, the second expression is evaluated and the result of the conditional expression is the value of the second expression. If the first expression's result is zero, the third expression is evaluated and the result of the conditional expression is the value of third expression.

The first expression can have any scalar type. The second and third expressions can be any of the following combinations:

  1. Both arithmetic.

    The usual arithmetic conversions are performed on the second and third expressions. The resulting type of the conditional expression is the result of the conversion.

  2. Both are pointers to type T.

    Arrays are converted to pointers, if necessary. The result is a pointer to type T.

  3. Identical type object.

    The types can match and be structure, union, or void. The result is that specific type.

  4. Pointer and Null pointer constant or a pointer to void

    One expression may be a pointer (or array that is converted to a pointer) and the other a null pointer constant or a pointer to void. The result is the same type as the type of the pointer operand.

In all cases, the result is not an lvalue.

Note that either the second or the third expression is evaluated, but not both. Although not required for readability, it is considered good programming style to enclose the first expression in parentheses. For example:

min = (val1<val2) ? val1:val2;

Example

This expression returns x if a is 0, or return y if a is not 0.

a == 0 ? x : y

The following statement prints "I have 1 dog." if num is equal to 1, or "I have 3 dogs.", if num is 3.

printf ("I have %d dog%s.\n",num, (num>1) ? "s" : "");
Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© 1996 Hewlett-Packard Development Company, L.P.