Question

This is code compiled with GCC(with -std=c99) and G++(with -std=c++98):

void fun()
{}
int main()
{
    fun(1,2,3);
    return 0;
}

GCC compiled the code successfully,but the G++ came up with this:
error: too many arguments to function ‘int fun()’
I am totally confused.
I knew that the C++ should be compatible with C by design,but this case shows me incompatibility.This case happens by design?

Was it helpful?

Solution

In C an empty parameter list means that you don't specify how many arguments the function takes. To define a function with 0 parameters, you'd use (void) as the parameter list. In C++ an empty parameter list means the function takes 0 parameters, so yes, C and C++ are not compatible in this instance.

I knew that the C++ should be compatible with C by design,but this case shows me incompatibility.This case happens by design?

While C++ is compatible to C in many instances, this is not the case all the time. Other examples are implicit casts from void* (allowed in C, but not in C++) and keywords (it's perfectly valid to use something like class as a variable name in C, but obviously not in C++ where it is a keyword). And yes, that's by design.

OTHER TIPS

In c++

void fun();

means a function taking no arguments. To communicate that to C write

void fun(void); // also works in c++ but it's frowned upon
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top