C varargs with default promotions: identify the error when passing floating values through an ellipsis and retrieving them with va_arg.\n\n#include <stdio.h>\n#include <stdarg.h>\n\nint main()\n{\n void display(int num, ...);\n display(4, 12.5, 13.5, 14.5, 44.3);\n return 0;\n}\nvoid display(int num, ...)\n{\n float c; int j;\n va_list ptr;\n va_start(ptr, num);\n for (j = 1; j <= num; j++)\n {\n c = va_arg(ptr, float); /* incorrect type for promoted argument */\n printf("%f", c);\n }\n}

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:

  • Function prototype: void display(int num, ...).
  • Call site passes four floating constants (type double by default).
  • Loop retrieves with 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

More Questions from Variable Number of Arguments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion