C Programming Language

Conditional operator

                  The conditional expression can be used as shorthand for some if-else statements. It is a 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...
if (x < y)
min = x;
min = y;
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.


Conditional Operator
Assignment operators Home Comma operators
c program stats