- 2068 Chaitra · 2 marks
Conditional operator vs if-else; digit sum
Short answer
The conditional operator (?:) is an expression that returns a value, compact for simple choices and usable inside larger expressions. The if-else statement is not an expression, cannot be embedded in expressions, and is better for blocks with multiple statements.
Differentiate between conditional operator and if-else statement.
Conditional operator (?:) | if-else statement |
|---|---|
| An operator that forms an expression and returns a value | A statement; does not return a value |
Syntax: x = (cond) ? a : b; | Syntax: if (cond) ... else ... |
| Compact, for simple choices | Better for long or multiple statements in a branch |
| Can be used inside another expression | Cannot be used inside an expression |
| Both branches must be expressions | Branches may contain any statements, loops, declarations |
| Hard to read when nested | Easy to read even when nested |
#include <stdio.h>
int main(void)
{
int a = 8, b = 3, big, big2;
big = (a > b) ? a : b; /* conditional operator */
if (a > b) /* if-else */
big2 = a;
else
big2 = b;
printf("%d %d\n", big, big2);
return 0;
}
Output:
8 8
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Compare switch and if-else-if ladder · Computer Programming, chapter 5 · asked 2×
- Syntax of if...else · Computer Programming, chapter 5
- Operators; conditional operator · Computer Programming, chapter 3
- Sum of digits until single digit · Computer Programming, chapter 5 · asked 2×
- Nested if with flowchart · Computer Programming, chapter 5
- Contrapositive and inverse: snow statement · Discrete Structure, chapter 1
- Converse etc. of beach statement · Discrete Structure, chapter 1
- City class with operator overloading · Object Oriented Programming, chapter 5
- Converse, inverse, contrapositive of prime statement · Discrete Structure, chapter 1 · asked 2×