FrozenHeart
FrozenHeart

Reputation: 20756

Weird compilation output

I've just compiled this code:

void foo(int bar...) {}

int main()
{
   foo(0, 1);
   return 0;
}

And the compilation output was really weird:

g++ test.c

Output:

Nothing

and

gcc test.c

Output:

test.c:1:17: error: expected ';', ',' or ')' before '...' token

I know that there is no comma after parameter, this question about strange compilation output.

I understand why this is invalid in C, but cannot understand why it is valid in C++.

Upvotes: 11

Views: 429

Answers (4)

milleniumbug
milleniumbug

Reputation: 15814

No comma version is allowed in C++ to allow for f(...) Why?

Consider void f() {} In C this means "I accept anything" and in C++ this means "I accept nothing". ( void f(void) is "I accept nothing" in C)

In order to declare C "I accept anything" function in C++, you have to write extern "C" void f(...);

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

The other answer is correct (I upvoted), but just to give a reference [8.3.5 Functions clause 3]:

parameter-declaration-clause:

parameter-declaration-listopt...opt

parameter-declaration-list , ...

This means that the comma is optional in C++, but not in C. You can also write void foo(...) in C++, because the parameter declaration list is also optional.

As for the reason why, in C++ templates, test(...) is common when using SFINAE for a "catch-all" function. However, in C, there is no usage for foo(...) and hence it is illegal.

Upvotes: 11

AnT stands with Russia
AnT stands with Russia

Reputation: 320641

You simply stumbled upon on of the obscure differences between C and C++ language grammars. Yes, C++ allows your syntax, while C doesn't. In C++ the comma before ... is optional, while in C it is always required. That's all there is to it.

Upvotes: 4

user529758
user529758

Reputation:

The thing is C++ allows the

returntype funcname(optional_param...)

syntax for variadic functions, while C does not.

Upvotes: 7

Related Questions