- 2073 Chaitra · 2+3 marks
Operators; conditional operator
Short answer
The conditional operator (? :) is a ternary operator: condition ? expr1 : expr2. It evaluates to expr1 if condition is true, else expr2. Example: max = (a>b) ? a : b assigns the larger value.
What is operator? Describe the conditional operator in C with syntax and example.
An operator is a symbol that tells the compiler to perform a specific operation (arithmetic, logical, relational, etc.) on one or more operands. For example, in a + b the symbol + is the operator and a, b are operands.
Conditional operator (? :)
It is the only ternary operator in C (it takes three operands) and works like a short if-else.
Syntax: variable = (condition) ? expression1 : expression2;
If the condition is true, expression1 is evaluated; otherwise expression2 is evaluated.
Example:
#include <stdio.h>
int main(void)
{
int a = 12, b = 20, max;
max = (a > b) ? a : b;
printf("Maximum = %d\n", max);
printf("%s\n", (a % 2 == 0) ? "a is even" : "a is odd");
return 0;
}
Output:
Maximum = 20
a is even
Here (a > b) ? a : b gives 20 as the larger value, and the second statement chooses between two messages.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Conditional operator vs if-else; digit sum · Computer Programming, chapter 5
- Global vs local; & and * operators · Computer Programming, chapter 3
- Syntax of operator overloading · Object Oriented Programming, chapter 5 · asked 4×
- Regression: operator experience and performance · Probability and Statistics, chapter 5
- Binary and unary operator overloading · Object Oriented Programming, chapter 5
- City class with operator overloading · Object Oriented Programming, chapter 5