C – Conditional Operator 2017-08-05T17:48:13+00:00

Conditional Operator:

  • The conditional expression can be used as shorthand for some if-else statements.
  • Conditional operator is also called as ternary operator.
  • This operator consist of two symbols: the question mark (?) and the colon (:).

The general syntax of the conditional operator is:
Identifier = (test expression)? Expression1: Expression2 ;

This is an expression, not a statement, so it represents a value. The operator works by evaluating  test expression. If it is true (non-zero), it evaluates and returns expression1. Otherwise, it evaluates and returns expression2.

The classic example of the ternary operator is to return the smaller of two variables. Every once in a while, the following form is just what you needed. Instead of…

You just say…
min = (x < y) ? x : y;

Suppose that x and y are integer variables whose values are 100 and 4, respectively. After executing above statement, the value of min is 4.

This is the only operator in C that makes use of three operands. It test condition corresponding to test expression, if it is true the value corresponding to Expression1 and it is false it corresponds to the value of Expression2.

Example :

Output :

Enter first number


Enter second number


Enter 1 for addition or 2 for multiplication


The result is 30

Prev Next