return 语句在 C 中是如何工作的? [英] How does the return statement work in C?

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

问题描述

我有一个关于 C 中的 return 语句的问题,它是从哪里真正返回的:

I have a question about return statement in C, from where it really returns:

int base(int a)
{
   if(a == 1)
     return 0;
}

int inherit()
{
   base(1);
   // the rest of the code
}

所以在inherit()函数中,base()被调用,它执行return 0,在这种情况下;inherit() 中的其余代码是否仍然执行?return 语句是如何工作的?

So within the inherit() function, base() is called, and it executes return 0, in this case; does the rest of code in inherit() still execute? How does the return statement really work?

推荐答案

你的代码太少了,不方便.我会更开心:

Your code is a little too minimal for comfort. I'd feel happier with:

int base(int a)
{
    if (a == 1)
        return 0;
    return 37;
}

int inherit(void)
{
    int n = base(1);
    printf("Base(1) is %d\n", n);
    return n + 3;
}

inherit()调用base()时,存储其当前状态,运行base()函数,并返回一个值.在此代码中,返回值被捕获在一个变量 n 中,然后在 printf() 调用和 return 中使用inherit().这就是 return 的工作原理:它单方面停止当前函数的执行并继续调用函数.

When inherit() calls base(), its current state is stored, the function base() is run, and it returns a value. In this code, the return value is captured in a variable, n and that is then used in the printf() call and the return within inherit(). That's how return works: it unilaterally stops the execution of the current function and continues in the calling function.

即使在 main() 中,return 也会终止当前函数并向调用函数返回一个值,也就是 C 运行时——C 运行时确保进程退出,通常将返回值传递给环境"(例如 Unix 上的 shell 程序).

Even in main(), a return terminates the current function and returns a value to the calling function, which is the C runtime — and the C runtime ensures that the process exits, usually relaying the returned value to the 'environment' (a shell program on Unix, for example).

请注意,修改后的代码确保 base() 始终返回一个值.不这样做通常会导致未定义的行为.如果该函数仅以 1 值作为参数被调用,那将是OK",但是你为什么要首先调用该函数.因此,始终确保如果一个函数应该返回一个值,则该函数的所有返回(尤其包括函数末尾的那个)都会返回一个值.在原始代码中,末尾没有 return —— 这很糟糕!

Note that the revised code ensures that base() always returns a value. Not doing so would lead to undefined behaviour in general. If the function is only ever called with the value 1 as an argument, it would be 'OK', but then why are you calling the function in the first place. So, always ensure that if a function is supposed to return a value, all returns from the function (including, in particular, the one at the end of the function) returns a value. In the original code, there is no return at the end — that's bad!

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

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