当 main return 什么都没有时,为什么我在 linux c 中得到了 main 最后调用的函数的 return 值?
when the main return nothing, Why I got the return value of the last func called by main in linux c?
这是我在 linux 中的代码:
#include <stdio.h>
static int tt(void);
static int tt(void)
{
return 1;
}
int main(int charc,char **charv)
{
tt();
}
在shell:
$./a.out
$echo %?
为什么我的结果是“1”
在没有 return 值的情况下从非空函数返回是 undefined behavior。你不能依赖结果。
从C99标准开始,main
函数有一个特例。如果没有值是从 main
编辑的 return,则假定 return 值为 0。但是,您似乎是在 C89 模式下编译(这是 gcc 的默认模式),而这是不允许的。
如果我将此代码编译为 C89,我会收到一条关于未 return 值的警告。为了演示未定义的行为,如果我在没有优化的情况下进行编译,退出状态为 1,但如果我使用 -O3
进行编译,则退出状态为 96。
如果我在 C99 模式下编译,我不会收到任何警告,程序的退出状态为 0。
要在 C99 模式下编译,将标志 -std=c99
传递给 gcc。
这是我在 linux 中的代码:
#include <stdio.h>
static int tt(void);
static int tt(void)
{
return 1;
}
int main(int charc,char **charv)
{
tt();
}
在shell:
$./a.out
$echo %?
为什么我的结果是“1”
在没有 return 值的情况下从非空函数返回是 undefined behavior。你不能依赖结果。
从C99标准开始,main
函数有一个特例。如果没有值是从 main
编辑的 return,则假定 return 值为 0。但是,您似乎是在 C89 模式下编译(这是 gcc 的默认模式),而这是不允许的。
如果我将此代码编译为 C89,我会收到一条关于未 return 值的警告。为了演示未定义的行为,如果我在没有优化的情况下进行编译,退出状态为 1,但如果我使用 -O3
进行编译,则退出状态为 96。
如果我在 C99 模式下编译,我不会收到任何警告,程序的退出状态为 0。
要在 C99 模式下编译,将标志 -std=c99
传递给 gcc。