定义为 int 但主体中没有 return 语句的 C 函数仍然可以编译 [英] C function defined as int but having no return statement in the body still compiles

查看:39
本文介绍了定义为 int 但主体中没有 return 语句的 C 函数仍然可以编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个这样的 C 代码:

Say you have a C code like this:

#include <stdio.h>

int main(){
    printf("Hello, world!
");
    printf("%d
", f());    
}

int f(){

}

它用 gcc 编译得很好,输出(在我的系统上)是:

It compiles fine with gcc, and the output (on my system) is:

你好,世界!

14

但是……但是……这怎么可能?我认为 C 不会让你编译这样的东西,因为 f() 没有返回整数的 return 语句.为什么这是允许的?是 C 特性还是编译器遗漏,14 是从哪里来的?

But.. but.. how is that possible? I thought that C won't let you compile something like that because f() doesn't have a return statement returning an integer. Why is that allowed? Is it a C feature or compiler omission, and where did 14 come from?

推荐答案

在这种情况下,返回值取决于确切的平台,可能是返回寄存器中发生的任何随机值(例如 EAX 在 x86 上)在程序集级别.允许不显式返回值,但会给出未定义的值.

The return value in this case, depending on the exact platform, will likely be whatever random value happened to be left in the return register (e.g. EAX on x86) at the assembly level. Not explicitly returning a value is allowed, but gives an undefined value.

在这种情况下,14 是 printf 的返回值.

In this case, the 14 is the return value from printf.

这篇关于定义为 int 但主体中没有 return 语句的 C 函数仍然可以编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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