C/C++ 中"int main()"和"int main(void)"的区别

cc++server side programmingprogramming更新于 2024/9/8 1:48:00

C

在 C 编程语言中,如果函数签名没有任何参数,那么它可以接受多个参数作为输入,但 C++ 中并非如此。如果在 C++ 中将参数传递给这样的函数,编译将失败。这就是 int main() 和 int main(void) 在 C 中相同的原因,但 int main(void) 是更好的方法,它限制用户将多个参数传递给主函数。

示例 (C)

#include <stdio.h>
int main() {
   static int counter = 3;
   if (--counter){
      printf("%d ", counter);
      main(5);
   }
}

输出

2 1

示例 (C++)

#include <iostream>
using namespace std;
int main() {
   static int counter = 3;
   if (--counter){
      cout << counter;
      main(5);
   }
}

输出

main.cpp: In function 'int main()':
main.cpp:10:13: error: too many arguments to function 'int main()'
main(5);
^
main.cpp:5:5: note: declared here
int main()
^~~~

相关文章