C varargs diagnostics: point out the specific error(s) in this program using <stdarg.h>. Rewrite focuses on why ellipsis functions need a named parameter and a correct va_start anchor.\n\n#include <stdio.h>\n#include <stdarg.h>\nfun(...);\n\nint main()\n{\n fun(3, 7, -11.2, 0.66);\n return 0;\n}\nfun(...)\n{\n va_list ptr;\n int num;\n va_start(ptr, n); /* 'n' is not a named parameter here */\n num = va_arg(ptr, int);\n printf("%d", num);\n}

Difficulty: Easy

Correct Answer: Error: Invalid declaration of fun(...)

Explanation:


Introduction / Context:
This question examines correct use of C variable-argument functions (varargs) with . Specifically, it tests whether the function with ellipsis is declared and defined properly and whether va_start is anchored to a valid, named parameter that precedes the ellipsis. Understanding these rules prevents undefined behavior and compilation errors in real-world code such as logging or formatting routines.


Given Data / Assumptions:

  • A function is declared as fun(...); with no named fixed parameter.
  • The definition fun(...) also uses only an ellipsis.
  • va_start(ptr, n) uses an identifier n that is not a parameter.
  • Old-style (K&R) return type is omitted.


Concept / Approach:
In standard C, a variadic function must have at least one fixed, named parameter before .... The macro va_start requires that the second argument be that last named parameter. Using only ... makes it impossible to position the va_list at the first variable argument. Therefore, such a declaration/definition is invalid. Missing an explicit return type is also an error in modern C, but the most fundamental issue is the invalid variadic signature.


Step-by-Step Solution:
Identify function signature: fun(...) → no named parameter → invalid for varargs.Check va_start(ptr, n)n is not a parameter → misuse of va_start.Conclusion → declaration/definition of fun(...) is invalid.


Verification / Alternative check:
Correct pattern: void fun(int count, ...)va_list ap; va_start(ap, count);This compiles and allows safe extraction of arguments with va_arg.


Why Other Options Are Wrong:
Error: fun() needs return type — true in modern C, but not the primary varargs error being tested. Error: ptr Lvalue requiredptr is a proper lvalue; the issue is not lvalueness. No error — incorrect; there is a clear signature misuse.


Common Pitfalls:
Forgetting the required named parameter, anchoring va_start to an identifier that is not a parameter, and assuming legacy implicit-int rules still apply.


Final Answer:
Error: Invalid declaration of fun(...)

More Questions from Variable Number of Arguments

Discussion & Comments

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