Re: What value and type should my functions return?
In article <goq12f$cl1$1@news.datemas.de>,
Victor Bazarov <v.Abazarov@comAcast.net> wrote:
Jeff Schwab wrote:
dwightarmyofchampions@hotmail.com wrote:
Hello. I am currently learning the C++ language, and I'm having
trouble with functions. Generally speaking, should my functions be
returning bool, void, or int?
There's no "generally speaking" here. The appropriate return type
varies wildly from one function to the next.
And how is my main function supposed to
handle errors in my function definitions?
By catching exceptions.
#include <cstdlib>
OOH you say "no generally speaking", OTOH you say "usually"... In
fact there is no single correct recommendation, like "by catching
exceptions". Depends on the QoI of the compiler. C++ exception
handling *can* be expensive. It *can* be much cheaper (quicker)
to return 'false' in case of an incomplete operation while
returning the result in a variable passed by reference, instead of
setting up the 'try-catch' mechanism in the caller. If your
function is called many millions of times, consider the performance.
bool foo_rc();
int main()
{
bool error_flag = false;
for(int i = 0; i < 1000000 ; ++i)
{
if(!foo_rc())
{
error_flag = true;
break;
}
}
if(error_flag)
{
// handle error
return -1;
}
return 0;
}
void foo_except();
int main()
{
try
{
for(int i = 0; i < 1000000; ++i)
{
foo_except();
}
}
catch(...)
{
// handle error
return -1;
}
return 0;
}
Seems to me like a nice example that exception code "can" be faster than
return status based code. In an example like the above, there's a spare
100000 if() that get executed but is not needed in the exception
version. Of course, the effect changes if the try-catch really needs
to be inside the for loop but that would be a bit braindead me think.
So seems like in a case like that, exceptions lead to faster and more
readable code.
Yannick