• Home
  • 3.21 Conditional / Ternary Operator

3.21 Conditional / Ternary Operator

View Categories

3.21 Conditional / Ternary Operator

< 1 min read

Table of Contents

The conditional operator ?: provides a compact way to select one of two expressions based on a condition.

#include <stdio.h>

int main()
{
    int a = 10;
    int b = 20;
    int greater;

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

    printf("Greater value = %d\n", greater);

    return 0;
}

Example Output #

Greater value = 20

Explanation #

The conditional operator has three operands:

condition ? expression1 : expression2

In the example:

(a > b) ? a : b

a > b is the condition. Since 10 > 20 is false, the expression after : is selected:

b

Therefore, greater receives the value 20.

Only one of the two result expressions is evaluated.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *