如果没有 return 语句,这个 C int 函数如何工作? [英] How does this C int function works without a return statement?

查看:26
本文介绍了如果没有 return 语句,这个 C int 函数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 C 代码,我确信它不会工作,但确实可以.

I've this C code which I was sure it wouldn't work, but it does.

#include <stdio.h>

int* find (int* a, int val) {
    if (*a == val)
        return a;
    else
        find(a+1, val);
}

int main() {
    int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int *b;

    b = find(a, 7);

    printf("%d
", *b);

    return 0;
}

当然,我收到了来自 gcc 的警告,因为它在 find 函数的 else 分支中缺少 return 语句.但是,它可以完美运行.

Of course, I get a warning from gcc since it lacks a return statement inside the else branch of the find function. However, it works perfectly.

为什么会这样?它怎么知道通过递归函数返回一个int?当然,最后一次调用返回一个 int,但我在 void 上下文中调用它.

Why does this happen? How does it know to return an int through the recursive function? Of course, the last calls returns an int, but I'm calling it in a void context.

推荐答案

假设你打算写 find 而不是 trova (我知道学习意大利语会派上用场有一天:),答案是这并不完美.它起作用"纯粹是偶然的,是由于未定义的行为.

Assuming that you meant to write find instead of trova (I knew learning Italian would come in handy some day :), the answer is that this does not work perfectly. It "works" purely by chance, by virtue of undefined behavior.

最有可能的是,最深的递归调用将返回值推送到某个寄存器中,更高级别的调用不会触及这些寄存器,因为它们没有返回语句,当调用者检查该寄存器时,返回值最深的呼唤还在.不过,你不能依赖这个.

Most likely, the deepest recursive call pushes the return value into some register, which the higher-level calls don't touch because they don't have a return statement, and when the caller inspects that register, the return value of the deepest call is still there. You can't rely on this, though.

这篇关于如果没有 return 语句,这个 C int 函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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