我只是在阅读
ISO/IEC 9899:201x 委员会草案 - 2011 年 4 月 12 日
我在 5.1.2.2.3 程序终止下找到的
..reaching the } that terminates the main function returns a value of 0.
表示如果在main()
中没有指定return语句,如果程序运行成功,那么main的右大括号}会返回0。
但在下面的代码中我没有指定任何返回语句,但它没有返回 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 中,返回的状态是未定义的。
您可以通过将 -std=c99
传递给 gcc 来启用它。
顺便说一句,有趣的是返回了 9,因为它是 printf
的返回,它只写了 9 个字符。
https://stackoverflow.com/questions/8677672/