为什么不在C中使main()无效? [英] Why not void main() in C?
问题描述
高手,我的代码在这里:
Hi expert, My c code is here:
#include<stdio.h>
void main(){
printf("Hello world");
}
代码块显示错误:
The codeblock shows the error:
||warning: command line option '-Wzero-as-null-pointer-constant' is valid for C++/ObjC++ but not for C [enabled by default]|
C:\Users\Amir Khasru\Desktop\pointers.c|2|error: return type of 'main' is not 'int' [-Wmain]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
我尝试过:
我试图通过codeblock编译上面的代码虽然没有成功。请解释一下?
What I have tried:
I tried to compile the above code through codeblock though never succeed. Please explain this?
推荐答案
因为 main 必须返回一个int。
参见 ISO / IEC 9899 (C99)和 ISO / IEC 9899:201x (C11)§ 5.1.2.2.1程序启动:
Because main have to return an int.
See ISO/IEC 9899 (C99) and ISO/IEC 9899:201x (C11) at §5.1.2.2.1 Program startup:
程序启动时调用的函数名为main。该实现为此函数声明没有
原型。它应该用返回类型int定义,并且没有
参数:
int main(void){/ * ... * /}
或带有两个参数(这里称为argc和argv,但任何名称可能都是使用
,因为它们是声明它们的函数的本地名称) ):
int main(int argc,char * argv []){/ * ... * /}
或等价物; 10或者以其他一些实现定义的方式。
The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
您可以使用2个参数 int argc 和 char * argv [] ,或者什么也没有。但是根据所有现行标准,回报不能无效。
无论如何,一些编译器允许形式 void main(void){/ * ... * /} as 私有扩展不符合标准。
You can define main with the 2 parameters int argc and char *argv[], or nothing. But the returns, as per all current standards, cannot be void.
Anyway some compilers allow the form void main(void) { /* ... */ } as private extension not standard compliant.
从C语言的角度来看,此代码完全合法。
From a C language point of view, this code is perfectly legal.
#include<stdio.h>
void main(){
printf("Hello world");
}
所以唯一的可能是编译器不符合C语言或不能在C模式下运行。正如 PIEBALDconsult
所说,它依赖编译器。
So the only possibility is that the compiler do not conform to C language or do not run in C mode. As PIEBALDconsult
said, "It is compiler dependent".
这篇关于为什么不在C中使main()无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!