return in void function()
Jul 24, 2011 at 3:31pm UTC
Hello,
i would like to ask when we have a function like:
1 2 3 4
void func(){
/* code code code*/
return ;
}
Is it "better" to use return at the end of the function or to program it without using return ?
1 2 3
void func(){
/* code code code*/
}
Thanks.
Jul 24, 2011 at 3:36pm UTC
The main reason to use "return" in a void function is to avoid executing the rest of the function in the case of an error or completion. Consider the following simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
void eval(int answr); //Forward declaration
int main()
{
int answr;
std::cout << "What is 2 + 2? " ;
std::cin >> answr;
eval(answr);
return 0;
}
void eval(int answr)
{
if (answr != 4)
{
std::cout << "\nWRONG" ;
return ; //SKIP THE REST OF THE FUNCTION
}
else
{
std::cout << "\nCORRECT!" ;
}
}
Jul 24, 2011 at 4:18pm UTC
Having a return statement as the last line in a void function exhibits the exact same behavior/execution time as simply excluding it.
Jul 24, 2011 at 5:06pm UTC
Thanks for the useful information.
Topic archived. No new replies allowed.