C与C++的函数声明中省略参数的不同意义

一直都以为C/C++中形如

int func();

这样的函数声明其意义就是一个参数 void(没有参数)的函数。然而今天在看C++的时候突然看到这么一句:

对于带空参数表的函数,C和C++有很大的不同。在C语言中,声明
int func2();
表示“一个可带任意参数(任意数目,任意类型)的函数”。这就妨碍了类型检查。而在C++语言中它就意味着“不带参数的函数”。

这一点老师并没有讲到,学校教科书里也没有提到,带着好奇心,我特意试了一下

test.c

 1 #include <stdio.h>
 2 
 3 void fun();
 4 int main()
 5 {
 6     fun(1, 1);
 7 
 8     return 0;
 9 }
10 
11 void fun(int a, int b)
12 {
13     printf("%d\n", a+b);
14 }
编译通过
$ gcc -Wall test.c -o test
$ ./test
2
$ mv test.c test.cpp
$ g++ -Wall test.cpp -o test
test.cpp: 在函数‘int main()’中:
test.cpp:6:10: 错误:too many arguments to function ‘void fun()’
  fun(1, 1);
  ^
test.cpp:3:6: 附注:在此声明
 void fun();
      ^~~

这也解释了为什么主函数要写成这样的原因

int main(void)

 

posted @ 2017-11-16 21:32  菜鸟明  阅读(3902)  评论(0编辑  收藏  举报