Function call in C

Possible duplicate:
Why does gcc allow arguments to be passed to a function that has no arguments?

code:

#include <stdio.h> #include <stdlib.h> void test_print() { printf("test print\n"); } int main() { test_print(1,2); return 0; } 

although the caller test_print in the main has a different number of arguments with protection for this function, the code may work very well, but if you change it to a C ++ version, a compilation error "too many arguments for funciton" ... "occurs. why does C allow the argument function inconsistencies, when can we use this method of calling? and why is this forbidden in C ++.

Ubuntu 11.10 system
compiler: gcc 4.6.1

+4
source share
4 answers

In c empty () function means that a function can take any number of arguments. If you want to indicate that the function does not accept any arguments, you need to:

 void test_print(void) 

While in C ++, an empty () function means that it does not accept any arguments. Please note that this is important in C ++, because in C ++ you can overload a function based on the number of arguments it can take.

+4
source

Because according to standard C,

 int foo(void); //Is the only way a function won't allow any parameters 

Standard Indication:

10 A special case of an unnamed parameter of type void as the only element in the list indicates that the function has no parameters.

Leaving an empty bracket means missing or any number of arguments.

+3
source

When you write:

 void test_print() { ... } 

you did not provide a function prototype, so the compiler should not compare calls with a list of arguments. To provide a prototype, you must write an explicit void :

 void test_print(void) { ... } 

Or provide a separate prototype declaration:

 void test_print(void); 

But it’s best if the function definition matches the prototype declaration, so always write void . And yes, this is one area where C ++ differs from C. You cannot use a function in C without a prototype in scope, and C ++ can treat an empty argument list as an empty argument list. On C99 or later, it is assumed that you have a prototype in scope, but it is usually not used by the compiler unless you add more stringent parameters ( -Wmissing-prototypes -Wstrict-rprototypes -Wold-style-definition -Wold-style-declaration - possible options for GCC). But the requirements of backward compatibility with the preliminary C standard meant that C89 cannot force the use of “empty parentheses”, this means that there are no arguments without breaking much of the previously valid C code, which would prevent the standard from being acceptable.

+2
source

This is a good programming discipline to make sure you find a compiler parameter that ensures that all functions are declared with a full prototype before use, and to use the compiler parameter all the time, and heed its warnings

0
source

All Articles