ProgrammingSystem Programmer

Describe the differences between functions with a variable number of arguments and standard functions in C. How to implement a function with a variable number of arguments?

Pass interviews with Hintsage AI assistant

Answer

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; }

Trick Question

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.

Examples of real errors due to misunderstanding the subtleties of the topic


Story

In a large project, a function with a variable number of arguments was used, but the type of passed values was not checked. It was expected that all arguments would be of type int, but once a double was passed, leading to incorrect memory reading and a random application crash.

Story

One developer forgot to call 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.