c
  1. c-conditional-operator

C Conditional Operator

The conditional operator is a ternary operator in C that takes three operands and is used to evaluate a Boolean expression. It is represented by a question mark (?) and a colon (:), and it is used to execute different code depending on a condition.

Syntax

condition ? expression1 : expression 2;

Example

#include <stdio.h>

int main() {
   int num = 10, result;
   result = (num > 5) ? 100 : 200;
   printf("Value of variable 'result' is: %d\n", result);
   return 0;
}

Output

The output of the above example will be:

Value of variable 'result' is: 100

Explanation

In the above example, the conditional operator is used to evaluate the Boolean expression num > 5. If the expression is true, then the value of result will be 100; otherwise, it will be 200.

Use

The conditional operator can be useful in situations where you need to perform a simple decision based on a Boolean expression. It is commonly used to assign a value to a variable based on a condition. It can also be used to replace simple ifelse statements.

Important Points

  • The conditional operator is a ternary operator that takes three operands.
  • It is used to evaluate a Boolean expression and execute different code depending on the result.
  • The syntax of the conditional operator is condition ? expression1 : expression2.
  • The conditional operator can replace simple if...else statements in some cases.
  • The conditional operator is evaluated from left to right.

Summary

In summary, the conditional operator is a ternary operator that is used to evaluate a Boolean expression and execute code based on the result. It is a powerful tool that can simplify code by replacing simple if...else statements. Understanding how to use the conditional operator can improve your coding efficiency and help you write cleaner, more concise code.

Published on: