Difficulty: Easy
Correct Answer: Error: var c data type mismatch
Explanation:
Introduction / Context:
This problem targets the rule of default argument promotions in C varargs. When arguments are passed through an ellipsis, float
values are promoted to double
, and integer types narrower than int
are promoted to int
. Failing to read them with the correctly promoted type leads to undefined behavior and typically wrong outputs.
Given Data / Assumptions:
void display(int num, ...)
.double
by default).va_arg(ptr, float)
.
Concept / Approach:
Because of the default promotions, any float
passed via ...
becomes double
. The receiving code must therefore use va_arg(ptr, double)
. Storing into a float
variable is fine after that conversion, but the type specified to va_arg
must match the promoted type exactly.
Step-by-Step Solution:
At call: literals 12.5, 13.5, 14.5, 44.3 → type double.Default promotions in varargs → remain double.Correct retrieval → c = (float)va_arg(ptr, double);
Given code uses va_arg(ptr, float)
→ mismatch → undefined behavior.
Verification / Alternative check:
Compile with warnings (e.g., -Wformat=2 -Wvarargs
) or instrumented sanitizers to observe misreads. Correcting to double
yields stable output.
Why Other Options Are Wrong:
Invalid va_list declaration — declaration is fine. No error options ignore the promotion rule and would print garbage on many platforms.
Common Pitfalls:
Retrieving float
instead of double
from varargs, and mixing integer and floating types without a controlling count or format string.
Final Answer:
Error: var c data type mismatch
Discussion & Comments