C/C++ 中的“int main()”和“int main(void)”的区别?
有时我们看到主函数定义有两种类型。int main() 和 int main(void)。那么有什么区别吗?
在 C++ 中,没有区别。在 C 中两者也是正确的。但第二个在技术上更好。它指定函数不接受任何参数。在 C 中,如果某个函数没有指定参数,那么它可以使用无参数或任意数量的参数来调用。请检查这两个代码。(请记住这些代码是用 C 编写的,而不是 C++)
示例
#include<stdio.h> void my_function() { //some task } main(void) { my_function(10, "Hello", "World"); }
输出
This program will be compiled successfully
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include<stdio.h> void my_function(void) { //some task } main(void) { my_function(10, "Hello", "World"); }
输出
[Error] too many arguments to function 'my_function'
在 C++ 中,两个程序都会失败。由此我们可以理解,在 C 中 int main() 可以使用任意数量的参数来调用。而 int main(void) 则不允许使用任何参数。
广告