Sometimes you need a value that depends on a condition, such as “pass” or “fail”. The conditional operator does this in a single expression. The comma operator, in contrast, lets several expressions run one after another where only one expression is allowed.
The conditional operator
The conditional operator is C’s only operator with three operands, so it is also called the ternary operator.
Example
Meaning
x = (y < 20) ? 9 : 10;
x is 9 if y < 20, otherwise 10
printf("%s\n", marks >= 50 ? "Passed" : "Failed");
Prints Passed or Failed
max = (a > b) ? a : b;
The larger of a and b
It has very low precedence, just above assignment, so b = (a < f) ? 1 : 0; is the safe way to assign a conditional value.
The comma operator
The comma operator evaluates its left operand, discards its value, then evaluates its right operand; the value of the whole expression is the value of the right operand. Evaluation is strictly left to right.
x = (y = 2, y - 1); first sets y to 2, then evaluates y - 1, so x becomes 1. The parentheses are needed because the comma has the lowest precedence of all operators.
The most common use is in a for loop (Unit 3): for (i = 0, j = n; i < j; i++, j--).
Not every comma is the comma operator: the commas in int a, b; and in printf("%d %d", a, b) are separators.
Key takeaways
?: is the only ternary operator: condition ? value_if_true : value_if_false.
Only one branch of ?: is evaluated.
Put the whole conditional on the right of =: b = (a < f) ? 1 : 0;.
The comma operator evaluates left to right and yields its rightmost value; it has the lowest precedence.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a single statement using the conditional operator that stores the absolute value of an integer n in abs_n, and trace it for n = −7.
Show worked answer
abs_n = (n < 0) ? -n : n;. For n = −7: the condition −7 < 0 is true, so only -n is evaluated, giving 7. Therefore abs_n is 7, and n itself is unchanged.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-types-operators-and-expressions/conditional-and-comma-operators/ to read this page.