0
0
Cprogramming~10 mins

Ternary operator in C - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Ternary operator
Evaluate condition
Yes/No
True expr
Result assigned
The ternary operator checks a condition, then chooses one of two expressions to evaluate and assign based on that condition.
Execution Sample
C
int a = 5;
int b = 10;
int max = (a > b) ? a : b;
printf("%d", max);
This code uses the ternary operator to assign the larger of a and b to max, then prints max.
Execution Table
StepCondition (a > b)Condition ResultExpression ChosenValue Assigned to maxOutput
15 > 10Falseb10
2N/AN/AN/AN/A10
💡 Condition is false, so b is chosen; max is assigned 10; program prints 10 and ends.
Variable Tracker
VariableStartAfter Step 1Final
a555
b101010
maxuninitialized1010
Key Moments - 2 Insights
Why does max get the value of b and not a?
Because the condition (a > b) is false (5 is not greater than 10), so the ternary operator chooses the expression after the colon, which is b, as shown in execution_table step 1.
Is the condition evaluated before choosing the expression?
Yes, the condition is evaluated first. Only one of the two expressions is evaluated based on the condition result, as shown in the concept_flow and execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of max after step 1?
A5
B10
Cuninitialized
D15
💡 Hint
Check the 'Value Assigned to max' column in execution_table row for step 1.
At which step is the condition (a > b) evaluated?
AStep 1
BStep 2
CBefore Step 1
DNever
💡 Hint
Look at the 'Condition (a > b)' column in execution_table to see when it is evaluated.
If a was 15 and b was 10, what would max be assigned?
A10
B5
C15
D0
💡 Hint
Refer to variable_tracker and execution_table logic: if condition is true, max gets a.
Concept Snapshot
Syntax: condition ? expr_if_true : expr_if_false;
Evaluates condition first.
If true, evaluates and returns expr_if_true.
If false, evaluates and returns expr_if_false.
Used for concise if-else assignments.
Full Transcript
The ternary operator in C evaluates a condition and chooses one of two expressions to assign or return. In the example, a is 5 and b is 10. The condition (a > b) is false, so the expression after the colon (b) is chosen. max is assigned 10. The program then prints 10. This operator is a short way to write if-else statements for simple choices.