C中的main函数是个另类(二)

上一次我们说明了C99 5.1.2.2.1 Program startup。今天我们继续对5.1.2.2.3 Program termination说明。

 

1. If the return type of the main function is a type compatible with int,

 

1.1a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;

 

用代码来说明:

  int status = main(argc, argv, envp);   /* Linux 下 */

  exit(status);

 

1.2 reaching the } that terminates the main function returns a value of 0.

 

理解:碰到结束括号},认为就是返回0。

推理:

1)int main()内可以不要写return语句。

 

代码验证

 

 

$ cat main.c

int main() { }

编译没有任何warning
$ gcc -Wall -std=c99 main.c

 

 

连续运行两次,退出状态都是0,不会是巧合吧。

 

$ ./a.out;echo $?

0

$ ./a.out;echo $?

0

对照一般的函数
$ cat foo.c
int foo() {}
编译有warning
$ gcc -Wall -std=c99 -c foo.c
foo.c: In function ‘foo’:
foo.c:1: warning: control reaches end of non-void function

 

所以,main函数就是不一般。

 

TODO: 查看gcc-4.2.4中对main特殊处理的代码

 

2. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

所以看来用void main()不好。
C FAQ中对void main的回答:
1.25b Is  void main() correct?
No, it's not correct.
来看一下代码
$ cat main_void.c
void main() {}
喔,编译warning
$ gcc -Wall -std=c99 main_void.c
main_void.c:1: warning: return type of ‘main’ is not ‘int’
连续两次运行,返回状态值在变,这可不好。我们搞软件的可不喜欢不确定性。
$ ./a.out;echo $?
4
$ ./a.out;echo $?
100
讨论
1)根据“SYSTEM V APPLICATION BINARY INTERFACE Intel386 Architecture”,Linux下函数返回值是在保存到eax。在void main的场合,exit(status)用到eax中垃圾值。
2) 如果只是自己的demo程序,用void main()也看不出有什么特别害处。
3) 一般Linux下,比如脚本内,用返回状态值==0认为正常,!=0为异常。用void main()做成的应用程序就不符合这种常规做法。
4) 其实,输入int比void还快一些。我个人就一直是用int main(今天测试代码出外)。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值