Conditional Operator or Ternary Operator in C

In this tutorial, you will learn Ternary Operator in C programming. In C, the ternary operator is also known as the conditional operator. We will explain the ternary operator with the help of some programming examples.

Ternary Operator in C:

The ternary operator is a shorthand way to express an if-else statement. Many C programmers use the ternary operator in place of if-else conditional statements.

The conditional operator takes three operands, that is why it is also called the ternary operator.

Its syntax is following,

expression_1 ? expression_2 : expression_3

 

Flow Chart of Ternary operator:

Following is a flow chart of the ternary operator.

Conditional Operator or Ternary Operator in C

The conditional or ternary operator works as follows:

✍ The first operand (expression_1) must be a scalar type (“single” value like integer, boolean). It is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). It means all side effects are completed before evaluation of the second or third operand.

✍  The second operand (expression_2) is evaluated if the first operand evaluates to a non-zero ( unequal to 0) value.

✍ The third operand (expression_3) is evaluated only if the first operand evaluates to zero (0),

 

The result of the conditional operator is the value of the second or third operand (whichever is evaluated).

Let’s understand the ternary or conditional operator through an example.

#include <stdio.h>

int main()
{
    int num1, num2;
    // Ask user to enter the two numbers
    printf("Please Enter Two different values\n");

    // Read two numbers from the user
    scanf("%d %d", &num1, &num2);

    const int GreaterNum =  (num1 > num2)? num1:num2;

    printf("Greater number is %d\n",GreaterNum);

    return 0;
}

Output:

Conditional Operator in C

 

In the above code, we are taking two numbers from the user. After taking numbers, we have used the ternary operator to find the largest number.

In the first expression, we are checking the largest number using the relational operator. If num1 is greater than num2, then the second expression will be evaluated and num1 assigned to another variable “GreaterNum” otherwise num2.

 

When to use a Ternary Operator?

Replace if-else statement:

The conditional operator is mostly used to replace the if-else statement for a simple conditional assignment statement.

For example, if you wish to implement a  C code to find positive and negative numbers. So you can replace the below code with a ternary operator.

#include <stdio.h>

int main()
{
    // Create a variable to get input
    int num;

    printf("Enter the num  = ");
    scanf("%d",&num); //Get the num
    if (num > 0)
    {
        printf("\nPositive Number\n");
    }
    else
    {
        printf("\nNegative Number\n");
    }

    return 0;
}

 

Replacing the code with a ternary operator,

#include <stdio.h>

int main()
{
    // Create a variable to get input
    int num;

    printf("Enter the num  = ");
    scanf("%d",&num); //Get the num

    (num > 0)? printf("\nPositive Number\n"):printf("\nNegative Number\n");


    return 0;
}

 

Initializing const:

The ternary operator is also useful to initialize const with different values. For example, if you wish to implement a C code to change the working hour’s normal hours from 8 to 6 on FRIDAY, you may use the below code,

const int workingHours = (day!=FRIDAY) ? 8 : 6;

 

Nested Ternary Operators:

You can also use nested ternary operators. Nested means ternary operator inside another ternary operator. Let’s see an example code using the nested ternary operator.

#include <stdio.h>

int main()
{
    // Create a variable to get input
    int n;

    printf("Enter the num  = ");
    scanf("%d",&n); //Get the num

    char *cPtr = ((n == 0)? "Zero":((n > 0)?"Positive": "Negative"));

    printf("%s\n",cPtr);

    return 0;
}

In the above example first condition we check whether a number is 0 or not. If the number is zero, then “Zero” will assign to the pointer otherwise next condition is evaluated to check whether the number is positive or negative.

 

Note: You should not use the ternary operator unnecessarily to make your code complex. You must concentrate on the readability and maintainability of your code.

 

Some important points related to conditional expressions (ternary operator):

The following points are important and you should remember these points.

1. Ternary operator has right-to-left associativity.

2. The first operand must be scalar type (evaluate zero or non-zero value)

3. The following rules apply to the second and third operands:

  • If both the second and third operands have arithmetic types, the usual arithmetic conversions are performed to convert them to a common type.
  • If both the operands have structure or union type, the result has that type.
  • If both operands have void type, the result has void type.
  • If both the second and third operands are pointers or one is a null pointer constant and the other is a pointer,  pointer conversions are performed to convert them to a common type.
  • If both operands are pointers to compatible types or to differently qualified versions of compatible types, the result type is a pointer to an appropriately qualified version of the composite type.  For example, see the following table, in which the first two columns are the second and third operands (in either order) the third column is the common type that is the result of a conditional expression:

condition expression in C

 

Recommended Post:

Leave a Reply

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