In C, functions can accept a fixed or variable number of arguments. Standard functions are defined as follows:
int sum(int a, int b) { return a + b; }
For a variable number of arguments, the <stdarg.h> macro is used, allowing for the handling of different numbers of input parameters.
Example:
#include <stdarg.h> #include <stdio.h> int sum(int count, ...) { int total = 0; va_list args; va_start(args, count); for (int i = 0; i < count; ++i) { total += va_arg(args, int); } va_end(args); return total; }
How do functions with a variable number of arguments differ from overloaded functions, and how to implement overloading in C?
Answer: C does not support function overloading as C++ does: the function name and number of arguments must be unique. Variable arguments implement a generic interface, but this is not "overloading".
Example (incorrect):
// This will not work in C, as you cannot create two functions with the same name: int foo(int a); float foo(float b); // Compilation error.
Story
Story
va_end, which led to resource leaks on some architectures. Symptoms only appeared after multiple uses of the function.Story
When handling a function with variable arguments, va_list was used twice without calling va_copy, which caused unpredictable behavior. The error did not manifest immediately, but only after changes in the compiler.