C/C++ 中的“int main()”和“int main(void)”的區別
C
在 C 程式語言中,如果函式簽名沒有任何引數,那麼它可以將多個引數作為輸入,但 C++ 中並非如此。如果在 C++ 中將引數傳遞給此類函式,則編譯將失敗。這是 C 中的 int main() 和 int main(void) 相同的原因,但 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() ^~~~
廣告