Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C. Syntax of the conditional operator is:
expression1 ? expression2 : expression3
The expression1 is evaluated first. If its value is true, then expression2 evaluates and expression3 is ignored. If expression1 evaluates to false, then expression3 evaluates and expression2 is ignored. The result will be a value of either expression2 or expression3 depending upon which of them evaluates.
Conditional operator associates from right to left.
Note :
The fact that only one of these two expressions evaluates is very important if they are expected to produce side effects!
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:
- Both expressions have to be of arithmetic type.
expression2andexpression3are subject to usual arithmetic conversions, which determines the resulting type. - Both expressions have to be of compatible
structoruniontypes. The resulting type is a structure or union type ofexpression2andexpression3. - Both expressions have to be of
voidtype. The resulting type isvoid. - Both expressions have to be of type pointer to qualified or unqualified versions of compatible types. The resulting type is a pointer to a type qualified with all type qualifiers of the types pointed to by both expressions.
- One expression is a pointer, and the other is a null pointer constant. The resulting type is a pointer to a type qualified with all type qualifiers of the types pointed to by both expressions.
- One expression is a pointer to an object or incomplete type, and the other is a pointer to a qualified or unqualified version of
void. The resulting type is that of the non-pointer-to-voidexpression.
Copyright (c) 2002-2013 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
What do you think about this topic ? Send us feedback!



