Grzegorz Szpetkowski Grzegorz Szpetkowski - 2 months ago 14
C++ Question

Variadic function without named argument

I noticed, that both GCC and MSVC are happy with the following code:

#include <iostream>
void foo(...);

int main()
{
foo();
}

void foo(...)
{
std::cout << "foo\n";
}


More specifically, code was run under GCC 6.2.0 and Visual Studio 2015.

I know that C requires at least one named parameter preceding the ellipsis, which allows to handle any number of arguments using specialized
va_start
,
va_args
, and
va_end
macros from
<stdarg.h>
(here
<cstdarg>
) header. Otherwise, it won't even compile.

Does C++ have some special treatment for "pure ellipsis" form or is it not suitable for fetching the arguments, i.e. it's allowed, but completely impractical?

Answer

C++ Variadiac arguments are explained here. This syntax is supported in C++, but the arguments are not accessible:

In the C programming language, at least one named parameter must appear before the ellipsis parameter, so printz(...); is not valid.

In C++, this form is allowed even though the arguments passed to such function are not accessible, and is commonly used as the fallback overload in SFINAE, exploiting the lowest priority of the ellipsis conversion in overload resolution. This syntax for variadic arguments was introduced in 1987 C++ without the comma before the ellipsis. When C89 adopted function prototypes from C++, it replaced the syntax with one requiring the comma. For compatibility, C++98 accepts both C++-style f(int n...) and C-style f(int n, ...)

Comments