C Ternary Operator Complete Tutorial

In this section, we will learn what the ternary operator is and how to use it in C.

Conditional Statement in C: Ternary Operator in C

The word `ternary` means 3 elements or 3 parts.

The `ternary` operator is the shorter version of the `if else` statement and is used to return a value but based on a condition.

This value then can be assigned to a variable, or be used as the return value of the `return` keyword, etc.

C Ternary Operator Syntax

Here’s the structure of the `ternary` operator:

variable = condition ? expression_True : expression_False;

Before explaining the items within this structure, let’s see the same version of this structure if we wanted to use the `if else` statement instead.

int variable; 

if (condition){
    variable  = expression_True;
}else{
    variable = expression_False
}

`variable`: variable can by any type of variable that we create and assign values to them.

Note: the `variable` is not part of the ternary operator, we just use it here to explain the details of this operator in a better way.

`condition`: Here we use those types of expressions that result either true or false. For example, is 4<10? Or is 100> 400? etc.

`expression_True`: if the `condition` resulted true, the value in this expression will be assigned to the `variable`.

`expression_False`: if the `condition` resulted false, the value in this expression will be assigned to the `variable`.

`?`: in order to separate the `condition` statement from the `expression_True` we use `?` symbol.

`:` : Also, in order to separate the `expression_True` from `expression_False` we use colon `:` symbol.

Example: Using Ternary Operator in C

#include <stdio.h>

int main() {

    int inValue ;

    printf("Please enter a number: \n");
    scanf("%d",&inValue);


    int check = inValue > 100 ? 100 : 10;

    printf("The value assigned to check-variable is: %d\n",check);

    return 0;
}

Compile and run the example above and enter an integer number.

How does ternary operator work in C?

If the entered number is greater than 100, then the condition is true in this ternary statement ` int check = inValue > 100 ? 100 : 10;` and the final value of the `ckeck` variable will be 100; otherwise, if the result of the condition is false (the entered value was less than 100) then the final value of the `check` variable will be 10.

That’s how `ternary` operator works.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies