考虑main()的以下两个定义。
int main()
{
/* */
return 0;
}
和
int main( void )
{
/* */
return 0;
}
有什么不同?
在C++中, 没有区别, 两者相同。
两种定义都可以在C中使用, 但是从技术上讲, 使用void的第二种定义在技术上被认为是更好的, 因为它明确指出main只能在没有任何参数的情况下调用。
在C语言中, 如果函数签名未指定任何参数, 则意味着可以使用任意数量的参数或不使用任何参数来调用函数。例如, 尝试编译并运行以下两个C程序(请记住将文件另存为.c)。注意fun()的两个签名之间的区别。
//Program 1 (Compiles and runs fine in C, but not in C++)
void fun() { }
int main( void )
{
fun(10, "GfG" , "GQ" );
return 0;
}
上面的程序可以编译并正常运行(请参阅这个), 但以下程序编译失败(请参见这个)
//Program 2 (Fails in compilation in both C and C++)
void fun( void ) { }
int main( void )
{
fun(10, "GfG" , "GQ" );
return 0;
}
与C不同, 在C++中, 上述两个程序均无法编译。在C++中, fun()和fun(void)都是相同的。
所以不同的是, 在C中int main()可以用任意数量的参数调用, 但是int main(无效)只能在没有任何参数的情况下调用。尽管大多数情况下并没有什么区别, 但是在C语言中建议使用” int main(void)”。
联系:
预测以下内容的输出
C程序。
问题1
#include <stdio.h>
int main()
{
static int i = 5;
if (--i){
printf ( "%d " , i);
main(10);
}
}
问题2
#include <stdio.h>
int main( void )
{
static int i = 5;
if (--i){
printf ( "%d " , i);
main(10);
}
}
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。
来源:
https://www.srcmini02.com/69403.html