为什么 main 在这里不返回 0? [英] Why main does not return 0 here?

查看:29
本文介绍了为什么 main 在这里不返回 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在阅读

ISO/IEC 9899:201x 委员会草案 - 2011 年 4 月 12 日

我在 5.1.2.2.3 程序终止下找到的

in which i found under 5.1.2.2.3 Program termination

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

表示如果在main()中没有指定return语句,如果程序运行成功,那么main的右大括号}会返回0.

it means if you don't specify any return statement in main(), and if the program runs successfully, then at the closing brace } of main will return 0.

但在下面的代码中我没有指定任何返回语句,但它没有返回 0

But in the following code i don't specify any return statement, yet it does not return 0

#include<stdio.h>
int sum(int a,int b)
{
return (a + b);
}

int main()
{
    int a=10;
    int b=5;
    int ans;    
    ans=sum(a,b);
    printf("sum is %d",ans);
}

编译

gcc test.c  
./a.out
sum is 15
echo $?
9          // here it should be 0 but it shows 9 why?

推荐答案

该规则是在 1999 版的 C 标准中添加的.在 C90 中,返回的状态是未定义的.

That rule was added in the 1999 version of the C standard. In C90, the status returned is undefined.

您可以通过将 -std=c99 传递给 gcc 来启用它.

You can enable it by passing -std=c99 to gcc.

顺便说一句,有趣的是返回了 9,因为它是 printf 的返回,它只写了 9 个字符.

As a side note, interestingly 9 is returned because it's the return of printf which just wrote 9 characters.

这篇关于为什么 main 在这里不返回 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆