D
dwightarmyofchampions
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? And how is my main function supposed to
handle errors in my function definitions?
As an example, suppose I have a function foo() return true if the
function had no errors and false if an error was encountered, like so:
bool foo()
{
// do some stuff
if (SomeError)
return false;
else
return true;
}
int main()
{
if (!foo())
{
std::cout << "An error occurred in function foo. Program
exiting..."
return 1;
}
// foo returned true, so we can move on
...
return 0;
}
Or I could have foo() have an int return type and return a zero if it
succeeded and a one if an error occurred, like so:
int foo()
{
// do some stuff
if (SomeError)
return 1;
else
return 0;
}
int main()
{
if (foo())
{
std::cout << "An error occurred in function foo. Exiting..."
return 1;
}
// foo returned zero, so execution was successful and we can move on
...
return 0;
}
Or I could have foo() return a void and have no error checking at all:
void foo()
{
// do some stuff
if (SomeError)
{
// do something to fix the error
}
// get to this spot regardless whether an error occurred or not
return;
}
int main()
{
foo();
...
return 0;
}
What is the generally accepted course of action for situations like
this?
trouble with functions. Generally speaking, should my functions be
returning bool, void, or int? And how is my main function supposed to
handle errors in my function definitions?
As an example, suppose I have a function foo() return true if the
function had no errors and false if an error was encountered, like so:
bool foo()
{
// do some stuff
if (SomeError)
return false;
else
return true;
}
int main()
{
if (!foo())
{
std::cout << "An error occurred in function foo. Program
exiting..."
return 1;
}
// foo returned true, so we can move on
...
return 0;
}
Or I could have foo() have an int return type and return a zero if it
succeeded and a one if an error occurred, like so:
int foo()
{
// do some stuff
if (SomeError)
return 1;
else
return 0;
}
int main()
{
if (foo())
{
std::cout << "An error occurred in function foo. Exiting..."
return 1;
}
// foo returned zero, so execution was successful and we can move on
...
return 0;
}
Or I could have foo() return a void and have no error checking at all:
void foo()
{
// do some stuff
if (SomeError)
{
// do something to fix the error
}
// get to this spot regardless whether an error occurred or not
return;
}
int main()
{
foo();
...
return 0;
}
What is the generally accepted course of action for situations like
this?