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:

  1. Both expressions have to be of arithmetic type. expression2 and expression3 are subject to usual arithmetic conversions, which determines the resulting type.
  2. Both expressions have to be of compatible struct or union types. The resulting type is a structure or union type of expression2 and expression3.
  3. Both expressions have to be of void type. The resulting type is void.
  4. 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.
  5. 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.
  6. 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-void expression.
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code