Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why calling a function that accepts no parameters with a parameter compiles in C but doesn't in C++

Tags:

c++

c

gcc

g++

Suppose I have this function:

void func() {}

When I call func with some parameters (e.g. func(132)), the C++ compiler yields an error, while the C compiler doesn't.

What is the difference between the two compilers in this case? And what advantages/disadvantages the C++ has by arising this error?

like image 445
Maroun Avatar asked Nov 26 '12 09:11

Maroun


People also ask

Can a function have no parameters in C?

If a function takes no parameters, the parameters may be left empty. The compiler will not perform any type checking on function calls in this case. A better approach is to include the keyword "void" within the parentheses, to explicitly state that the function takes no parameters.

How do you call a function with no parameters?

C static code analysis: Functions without parameters should be declared with parameter type "void"

What should be passed in parameters when function does not require any parameters?

What should be passed in parameters when function does not require any parameters? Explanation: When we does not want to pass any argument to a function then we leave the parameters blank i.e. func() – function without any parameter.

What happens when you create a function without any parameters?

Nothing will happen- meaning you won't get an error or a warning as passing the parameters in javascript is optional. All the parameters that weren't "supplied" will have the undefined value.


1 Answers

There are no advantages or disadvantages. C supports this for compatibility with K&R C from the 1980s. You might like this feature if you are still using code you wrote in the 1980s. You might dislike this feature if you want better diagnostics from your compiler.

void func();

In C, this means that func takes unspecified parameters.

If you need to specify that the function takes no parameters, write it this way:

void func(void);

In C++ the two prototypes are the same. (In C, only the second one is a prototype.) If you compile with GCC/Clang's -Wstrict-prototypes option, you will get warnings for using void func(); in C, as you should.

This is only about function declarations. In both languages, the following function definitions are the same:

// These two are the SAME
void func() { }
void func(void) { }

// These two are DIFFERENT
void func();
void func(void);
like image 82
Dietrich Epp Avatar answered Oct 23 '22 06:10

Dietrich Epp