“ int main()”和“ int main(void)”之间的C / C ++区别

C

在C编程语言中,如果函数签名没有任何参数,则它可以采用多个参数作为输入,但对于C ++而言,情况并非如此。如果将参数传递给C ++中的此类函数,则编译将失败。这是因为intmain()和int main(void)在C中相同,但是int main(void)是更好的方法,它限制了用户将多个参数传递给main函数。

范例(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()^~~~