Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you put an explicit "return;" at the end of a void function? [duplicate]

Tags:

c++

return

void

Is there has any different by putting or not putting return in the the last line of function?

void InputClass::KeyDown(unsigned int input)
{
    // If a key is pressed then save that state in the key array
    m_keys[input] = true;
    return;
}
like image 302
user Avatar asked Dec 06 '25 23:12

user


2 Answers

No, there is no difference !

return in void functions is used to exit early on certain conditions.

Ex:

void f(bool cond)
{
    // do stuff here
    if(cond)
        return;
    // do other stuff
}
like image 120
user1233963 Avatar answered Dec 09 '25 13:12

user1233963


There is functionally no difference in your example, if we look at the C++ draft standard section 6.6.3 The return statement paragraph 2 says:

A return statement with neither an expression nor a braced-init-list can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). [...] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

like image 22
Shafik Yaghmour Avatar answered Dec 09 '25 13:12

Shafik Yaghmour