Conditional Operator
? :
The conditional operator
? :
is the only ternary operator in C. Syntax of the con-
ditional operator is:
expression1 ? expression2 : expression3
Expression1
evaluates first. If its value is true, then
expression2
evaluates
and
expression3
is ignored. If
expression1
evaluates to false, then
expres-
sion3
evaluates and
expression2
is ignored. The result will be the value of
either
expression2
or
expression3
depending upon which evaluates. The fact
that only one of these two expressions evaluates is very important if you expect
them to produce side effects!
Conditional operator associates from right to left.
Here are a couple of practical examples:
/* Find max(a, b): */
max = (a > b) ? a : b;
/* Convert small letter to capital: */
/* (no parentheses are actually necessary) */
c = (c >= 'a' && c <= 'z') ? (c - 32) : c;
Conditional Operator Rules
Expression1
must be a scalar expression;
expression2
and
expression3
must obey one of the following rules:
1. Both of arithmetic type;
expression2
and
expression3
are subject to the
usual arithmetic conversions, which determines the resulting type.
2. Both of compatible struct or union types. The resulting type is the structure or
union type of
expression2
and
expression3
.
3. Both of
void
type. The resulting type is
void
.
MikroElektronika: Development tools - Books - Compilers
109
page
mikroC - C Compiler for Microchip PIC microcontrollers
mikroC
making it simple...