在void函数中返回的目的是什么

use*_*ser 2 c++

在函数的最后一行放入还是不放回头有什么不同吗?

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

use*_*963 11

不,没有区别!

返回的void函数用于早期在一定条件下退出.

例如:

void f(bool cond)
{
    // do stuff here
    if(cond)
        return;
    // do other stuff
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*our 8

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

不带表达式和braced-init-listreturn语句只能用于不返回值的函数,即返回类型为void的函数,构造函数(12.1)或析构函数(12.4) .[...] 离开函数末尾相当于没有值的返回; 这会导致值返回函数中的未定义行为.