Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions with empty parameter list in C99 is not compatible with C++98?

Tags:

c++

c

gcc

c99

c++98

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?

like image 232
richa.napo Avatar asked Nov 18 '25 22:11

richa.napo


2 Answers

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.

like image 120
sepp2k Avatar answered Nov 20 '25 13:11

sepp2k


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
like image 34
Nikos Athanasiou Avatar answered Nov 20 '25 11:11

Nikos Athanasiou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!