2

在函数的最后一行放置或不放置 return 有什么不同吗?

void InputClass::KeyDown(unsigned int input)
{
    // If a key is pressed then save that state in the key array
    m_keys[input] = true;
    return;
}
4

8 回答 8

11

不,没有区别!

void 函数中的return用于在某些条件下提前退出。

例如

void f(bool cond)
{
    // do stuff here
    if(cond)
        return;
    // do other stuff
}
于 2013-09-05T13:56:53.223 回答
8

如果我们查看C++ 草案标准部分,则您的示例在功能上没有区别6.6.3 。 return 语句第 2 段说:

既没有表达式也没有花括号初始化列表的return 语句只能用于不返回值的函数,即返回类型为 void、构造函数 (12.1) 或析构函数 (12.4) 的函数. [...]从函数末尾流出相当于没有值的返回;这会导致值返回函数中的未定义行为。

于 2013-09-05T13:58:16.917 回答
1

在您的特定代码中,不。但通常如果您想根据条件从函数中提前返回,请使用return.

void InputClass::KeyDown(unsigned int input)
{
    // If a key is pressed then save that state in the key array
    m_keys[input] = true;
    if(someCondition) //early return
       return;
   //continue with the rest of function 
   //.....
}
于 2013-09-05T13:56:40.963 回答
1

在这种特殊情况下,它绝对没有任何作用——它也不会导致任何问题(例如,假设编译器至少具有一些优化能力,则不会生成额外的代码)。

将 a 放在 void 函数的中间当然是有目的的return,这样函数的后面部分就不会被执行。

于 2013-09-05T13:57:22.510 回答
1

没有区别,在你的例子中,但如果你想更早地从函数返回以防万一,它很有用

于 2013-09-05T13:58:34.100 回答
1

returninvoid函数有多种作用:

  1. 过早结束函数执行(例如算法完成,不满足前提条件)

  2. 在某些情况下,您设计的算法使得 85% 的情况会更快结束。(因此执行速度更快)让其他 15% 的案例在返回之后进行(因此在一些罕见的竞争条件下运行速度较慢。

  3. 类似于goto end.

于 2013-09-05T14:07:17.737 回答
0

在这种情况下,什么都没有。在其他情况下,这可能是因为代码在 return 语句之后,而作者想让它“死”一段时间。之后应该删除它。

于 2013-09-05T13:56:33.693 回答
-1

不,它们是相同的东西。

使用返回;当你想退出功能。

于 2013-09-05T14:03:50.760 回答