ghosTzone
main(_){return _} && echo $? /* Keep It Simple Stupid | 本博客所有文章皆为原创 转载请注明 - ghosTM55 */

C语言误区之void main()

ghosTM55 posted @ 2008年11月22日 01:45 in C/C++ , 3816 阅读

  大学开学一个月了,看到了很多胡扯的老师和学生,具体的没必要浪费时间进行愤怒的驳斥了。先说说C语言的一个非常大的误区,在很多教材上都没有提到,甚至引用了这种错误的代码写法,就是著名的void main()问题。

  先来看一下这段看似正确的代码:

#include<stdio.h>
void main()
{
    printf("helloworld\n");
}

  然后使用gcc编译器进行编译,会提示警告:

txi@ghosTunix.org:test> gcc helloworld.c
helloworld.c: In function ‘main’:
helloworld.c:3: warning: return type of ‘main’ is not ‘int’

  不过没关系,程序照样能执行:

txi@ghosTunix.org:test> ./a.out
helloworld

  运行完全正确,但我们查看该程序的返回值会发现系统接受到了一个错误的返回值11:

txi@ghosTunix.org:test> echo $?
11

  可见,void main()其实根本就是一个错误的写法,系统在执行完这样一段程序后,得到的程序返回值是一个错误的返回值。

  在C语言的标准中,从来没有定义过void main()这样的写法,标准的main函数调用形式如下

#include<stdio.h>
int main(void)
{
    printf("helloworld\n");
    return 0;
}

  有了确切的返回值,程序能够在像用户需要的情况那样运行时,还能让系统很好的了解到程序已经成功或者错误地执行了。

txi@ghosTunix.org:~> date
Wed Oct 15 20:47:08 CST 2008


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter