Re: What value and type should my functions return?
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>
#include <iostream>
#include <stdexcept>
double divide(double dividend, double divisor) {
if (divisor == 0.0) {
throw std::range_error( "attempted division by zero" );
}
return dividend / divisor;
}
int main() try {
std::cout << "3.0 / 5.0 == " << divide(3.0, 5.0) << '\n';
std::cout << "3.0 / 0.0 == " << divide(3.0, 0.0) << '\n';
return EXIT_SUCCESS;
} catch (std::exception const& x) {
std::cerr << "error: " << x.what() << '\n';
return EXIT_FAILURE;
}
As an example, suppose I have a function foo() return true if the
function had no errors and false if an error was encountered
That's common in C, but it's usually the wrong thing to do in C++.
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.
Of course, there is no "generally" correct course of action. It
has to be measured.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask