C varargs correctness: spot the error involving parameter naming, shadowing, and va_start anchor in this display function.\n\n#include <stdio.h>\n#include <stdarg.h>\n\nint main()\n{\n void display(char *s, int num1, int num2, ...);\n display("Hello", 4, 2, 12.5, 13.5, 14.5, 44.0);\n return 0;\n}\nvoid display(char s, int num1, int num2, ...)\n{\n double c;\n char s; / shadows parameter and has wrong type /\n va_list ptr;\n va_start(ptr, s); / wrong anchor: must be last named parameter (num2) */\n c = va_arg(ptr, double);\n printf("%f", c);\n}

Difficulty: Easy

Correct Answer: Error: in va_start(ptr, s);

Explanation:


Introduction / Context:
This question probes two classic varargs mistakes: (1) va_start must be given the last named parameter in the function's parameter list, and (2) accidental shadowing of parameters with local variables. Both lead to broken argument retrieval and undefined behavior.


Given Data / Assumptions:

  • Function signature: void display(char *s, int num1, int num2, ...).
  • Inside the function, a local char s; shadows the pointer parameter char *s.
  • va_start(ptr, s) is used incorrectly.


Concept / Approach:
The second argument of va_start must be exactly the identifier of the last named parameter before the ellipsis. In this prototype, that is num2. Using s (and worse, a local variable that shadows the parameter) violates the contract; the runtime will compute the wrong starting address for the variable arguments. Shadowing also confuses readers and compilers, but the key semantic error here is the bad va_start anchor.


Step-by-Step Solution:
Parameter list ends with int num2 before ....Correct anchor: va_start(ptr, num2);Remove the conflicting char s; or rename it.Retrieve floating arguments as double due to default promotions.


Verification / Alternative check:
Fixing to va_start(ptr, num2) and removing the shadowed s produces stable output. Tools like sanitizers can help detect UB caused by wrong va_start.


Why Other Options Are Wrong:
Invalid arguments and too many parameters are generic and do not pinpoint the varargs rule being broken. No error is clearly incorrect.


Common Pitfalls:
Anchoring va_start to the wrong parameter, shadowing names, and forgetting default promotions.


Final Answer:
Error: in va_start(ptr, s);

More Questions from Variable Number of Arguments

Discussion & Comments

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