Menu Close

Ternary Conditional Operator in C Program

Posted in C Programming

The C ternary operator ?: is a shorthand way of writing an if-else statement in a single line. It is often used for simple conditional assignments. A ternary operatorcinvolves three operands in the operation

Syntax

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
condition ? expression_if_true : expression_if_false;
condition ? expression_if_true : expression_if_false;
condition ? expression_if_true : expression_if_false;

If the condition is true, the value of the expression before the colon (:) is returned; otherwise, the value of the expression after the colon is returned.

A ternary operator is commonly used within assignment statements

Following if-else statements

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if(a>b) max=a;
else max=b;
if(a>b) max=a; else max=b;
if(a>b) max=a;
else max=b;

can be rewritten into following assignment statements:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
max=(a>b)?a:b;
max=(a>b)?a:b;
max=(a>b)?a:b;

Example 1:  C ternary operator

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <stdio.h>
int main() {
int x = 10;
int y;
// Ternary conditional operator to assign a value to y
y = (x > 5) ? 20 : 30;
// Output the value of y
printf("The value of y is: %d\n", y);
return 0;
}
#include <stdio.h> int main() { int x = 10; int y; // Ternary conditional operator to assign a value to y y = (x > 5) ? 20 : 30; // Output the value of y printf("The value of y is: %d\n", y); return 0; }
#include <stdio.h>

int main() {
    int x = 10;
    int y;

    // Ternary conditional operator to assign a value to y
    y = (x > 5) ? 20 : 30;

    // Output the value of y
    printf("The value of y is: %d\n", y);

    return 0;
}

In this example, if x is greater than 5, y is assigned the value 20; otherwise, it is assigned the value 30. The result is printed using printf.

Result:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The value of y is: 20
The value of y is: 20
The value of y is: 20

Ternary Operator Key-Points

1.The ternary operator has a lower precedence than relational operators and arithmetic operators but higher than assignment operators. Therefore,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
max = (a > b) ? a : b;
max = (a > b) ? a : b;
max = (a > b) ? a : b;

can be written without parentheses as

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
max = a > b ? a : b;
max = a > b ? a : b;
max = a > b ? a : b;

2.The ternary operator ? and : are a pair of operators and cannot be used separately.

3. The associativity of the ternary operator is from right to left.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
a > b ? a : c > d ? c : d
a > b ? a : c > d ? c : d
a > b ? a : c > d ? c : d

should be understood as

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
a > b ? a : (c > d ? c : d)
a > b ? a : (c > d ? c : d)
a > b ? a : (c > d ? c : d)

Example 2 )  determining if an integer is greater than 6

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <stdio.h>
int main()
{
int y;
int x = 2;
y = (x >= 6) ? 6 : x; /* This is equivalent to: if (x >= 6) y = 6; else y = x; */
printf("y =%d ",y);
return 0;
}
#include <stdio.h> int main() { int y; int x = 2; y = (x >= 6) ? 6 : x; /* This is equivalent to: if (x >= 6) y = 6; else y = x; */ printf("y =%d ",y); return 0; }
#include <stdio.h>
int main() 
{
   int y;
   int x = 2;
   y = (x >= 6) ?  6 : x;  /* This is equivalent to:  if (x >= 6)    y = 6;  else    y = x; */
   printf("y =%d ",y);
   return 0;
}

Results:

Example 3) To determine the maximum value of two integers

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
main()
{
int a,b,max;
printf("\n input two numbers: ");
scanf("%d%d",&a,&b);
printf("max=%d",a>b?a:b);
}
main() { int a,b,max; printf("\n input two numbers: "); scanf("%d%d",&a,&b); printf("max=%d",a>b?a:b); }
main()
{
  int a,b,max;
  printf("\n input two numbers: ");
  scanf("%d%d",&a,&b);
  printf("max=%d",a>b?a:b);
}

This program prompts the user to enter two integers, then uses a conditional expression to determine which one is larger and prints the result.

How to Write a Good C Program Using Ternary Operator

  1. Readability:
    • While conditional expressions can make the code more concise, avoid excessive use in complex expressions to prevent a reduction in code readability.
  2. Nested Ternary Operators:
    • Avoid nesting multiple ternary operators in a single line, as it can make the code difficult to understand. Use if-else statements for more complex conditions.
  3. Side Effects:
    • Be cautious when using expressions with side effects inside a ternary operator, as the order of evaluation may not be intuitive.
  4. Type Consistency:
    • Ensure that the expressions on both sides of the ternary operator have consistent data types to prevent unexpected behavior.
  5. Overuse:
    • Use the ternary operator for simple and straightforward conditions. For more complex logic, favor the use of if-else statements for clarity.
  6. Clarity vs. Conciseness:
    • Prioritize code clarity over conciseness. Code maintainability is crucial, and overly complex expressions can hinder understanding.
  7. Grouping with Parentheses:
    • Use parentheses to group expressions for clarity, especially when combining multiple ternary operators in a single line.
  8. Understanding the Code:
    • Ensure that the code remains easily understandable to other developers who might read or maintain it.

Remember that while the ternary operator is a powerful tool for expressing simple conditions concisely, it should be used judiciously to maintain code quality and readability.

 

Leave a Reply