Reputation: 333
Consider the two simple functions
void foo()
{
// do stuff
return;
}
void bar()
{
// do same stuff as foo()
}
where the only difference between them is foo() contains a return statement and bar() will return after "dropping" out of the function (for a lack of better terms). I assume that the return statement just represents a jump in assembly back to the stored address right before the function call. But I am curious to know if there are any performance differences between the two methods, other than the time it takes to type the 7 extra characters :).
Upvotes: 2
Views: 671
Reputation: 12789
Looking at the Standard (working draft, 8.7.4 The return statement [stmt.return], emphasis mine):
A function returns to its caller by the
return
statement.
The expr-or-braced-init-list of areturn
statement is called its operand. Areturn
statement with no operand shall be used only in a function whose return type is cvvoid
, a constructor, or a destructor. A return statement with an operand of typevoid
shall be used only in a function whose return type is cvvoid
.
[...]
Flowing off the end of a constructor, a destructor, or a non-coroutine function with a cvvoid
return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main or a coroutine ([dcl.fct.def.coroutine]) results in undefined behavior.
There's no reason for a standard compliant compiler to generate different assembly codes for the two functions shown in the question, because they are equivalent.
So there won't be any perfomance difference, only different readability of the source code (unless you are following some weird code guideline, reviewers may very well ask you why a return
statement is there).
Upvotes: 0
Reputation: 85531
The compiler will always insert a RET
instruction at the end of a void
function (assuming it does not end by throwing an exception). An explicit return;
statement here is not needed, and will have no effect.
The generated assembly in your example is identical:
foo():
ret
bar():
ret
The explicit return
from a function is useful to exit the function early. For example:
void foo() {
// do some work ...
if (/* some condition */)
return;
// do more work ...
}
Upvotes: 2
Reputation: 17464
No.
There is an implicit return
at the end of a function with void
return type, if you don't type it.
Don't concern yourself with how function calls and returns are implemented; you're currently in the realm of the abstraction that is C++. You're not programming a computer; you're describing a program. Your executable is not a one-to-one mapping of source code lines to computer instructions (not even close).
As it happens, there is no real-world performance difference whether you write return
yourself or let it be implicit. Why would there be? The semantics are identical. They're the same program.
Upvotes: 3