Search code examples
c++variadic-functions

Is variadic arguments list null-terminated?


The title covers my question pretty much completely. For some context - from various sources I know that variadic functions are supposed to have signature where first argument gives information about how many arguments were passed, but after playing around with it a bit i found that vs_arg always returns nullptr right after the last argument so this code works well (with MS Visual Studio):

void func(MClass *t_instance...) {
    std::va_list arguments;
    va_start(arguments, t_instance);
    for (MClass *instance = t_instance; instance != nullptr; instance = va_arg(arguments, MClass *)) {
        std::out << instance->name << std::endl;
    }
    va_end(arguments);
}

Of course provided that there is no nullptr passed as an argument, is this a valid assumption? I couldn't find that this list is supposed to be null-terminated, but couldn't find the opposite either.


Solution

  • No, it is not a valid assumption that calling va_arg at the last parameter will return a null pointer. According to the standard* calling va_arg when there are no parameters left, i.e when it is pointing at the last parameter, has undefined behavior. As far as I know there is no way for the program to check when it is at the last parameter, this information must be provided by some other mean.

    * The C++ standard refers the behavior of va_arg to the C standard, which defines this in section 7.16.1.1 clause 2.