Search code examples
c++variadic-functions

Are functions with variadic arguments required to call va_start?


Is it safe to exit a function with variadic parameters early, before it begins using va_list?

#include <cstdarg>

int func(const char * format, ...){
    if(format == NULL)
        return 0; // <-- exits before acknowledging variadic parameters; is this okay?
    va_list params;
    va_start(params, format);

    // func body

    va_end(params);
    return stuff;
}

Solution

  • Yes, this is legal. No, functions are not required to call va_start. From the C99 standard:

    If access to the varying arguments is desired, the called function shall declare an object ... having type va_list.

    Notice two things here:

    1. A va_list is a prerequisite to the va_start call.
    2. A va_list is only necessary to have if access to the varying arguments is desired.

    As such, also the va_start call is only necessary if access to the varying arguments is desired.