Interview Questions
Variable Number of Arguments · Study material
Variable Number of Arguments – Interview Questions
1. How do you declare a function that takes a variable number of arguments?
With an ellipsis as the last parameter: int f(int n, ...). Before C23 at least one named parameter is required.
2. Which header and macros are used?
<stdarg.h>: va_list, va_start, va_arg, va_end and va_copy.
3. How does printf know how many arguments it received?
It doesn't – it trusts the format string. Each conversion specification consumes one argument.
4. Why can't va_arg read a float?
float arguments to ... are promoted to double, so they must be read as double. The same applies to char and short (read as int).
5. What does va_copy do?
Copies a va_list at its current position so the remaining arguments can be traversed again.
6. Why do vprintf and vsnprintf exist?
So that your own variadic functions can forward their arguments – ... cannot be passed on directly.
7. What happens if va_arg is called with the wrong type or too many times?
Undefined behaviour: the program may print garbage or crash.
8. What is __VA_ARGS__?
In a variadic macro, the placeholder for the arguments matched by .... C23 adds __VA_OPT__ to emit text only when there are such arguments.
9. Why cast NULL when it is used as a sentinel?
NULL may be defined as plain 0 (an int), which is not guaranteed to be passed like a pointer through ....
10. What changed for variadic functions in C23?
int f(...) with no named parameters is allowed, and va_start takes only the va_list.