Arduino - Conditional Operator ? :

The conditional operator ? : is the only ternary operator in C.

? : conditional operator Syntax

expression1 ? expression2 : expression3

Expression1 is evaluated first. If its value is true, then expression2 is evaluated and expression3 is ignored. If expression1 is evaluated as 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 as True.

Conditional operator associates from right to left.


/* 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;

Rules of Conditional Operator

  • expression1 must be a scalar expression; expression2 and expression3 must obey one of the following rules.
  • Both expressions have to be of arithmetic type.
  • expression2 and expression3 are subjected to usual arithmetic conversions, which determines the resulting type.
  • >Both expressions have to be of void type. The resulting type is void.
Kickstart Your Career

Get certified by completing the course

Get Started