Ternary or Condition operator explain with example

Ternary or Condition operator explain with example


The ? (ternary condition) operator is a more efficient form for expressing simple if statements. It has the following form:

  expression1 ? expression2:  expression3

It simply states:

if expression1 then expression2 else expression3

For example to assign the maximum of a and b to z:

  z = (a>b) ? a : b;

which is the same as:



  if (a>b) z = a;

  else z=b;

Labels: