C++ – Handling Bool Value With an If Statement

booleanc++if-statementqtreturn

I am a student programmer currently designing a GUI for my company with Qt and I have a rather simple question that I just cant seem to find the answer to on the web. It seems like someone has had to of asked it before so if you know where the answer is Id be happy with a reference. My question is; can a Boolean datatype in c++ be handled using an if statement. So a bool value is either one or zero so can you do something like this

bool trueOrFalse()
{
    myclass temp;
    QString tempstr;
    double candidate;
    bool validate;

    tempstr = ui->tableWidgetInjectionLocations->item(i,9)->text();
    candidate = tempstr.toDouble(&validate);
                if(validate == true)
                {
                    temp.tempProperty = candidate;
                }
                else
                {
                    QMessageBox error;
                    error.setText("Error");
                    error.exec();
                }
    if (validate == true)
       {
       return true;
       }
    else
       {
       return false;
       }
}

What I am really looking for here is in the last section of this bool function. When I use return am I actually returning a value that this function would then hold or am I using a the keyword return inappropriately? Once validation has past Id like to be able to use the function to indicate whether or not to proceed in another function Please keep my criticism constructive please. As a student I am only interested in improving.

Best Solution

The value you return using the return statement is literally returned whenever you call the function.

So if you write this code somewhere else in your program:

bool returnValue = trueOrFalse();

then the returnValue variable will contain a Boolean value equivalent to whatever was returned by the trueOrFalse() function.

The function itself doesn't "hold" the value, the caller of the function defines a variable that will hold the value after the function call has completed.


As for your second question, you are using the return statement correctly, but you can simplify your code in the trueOrFalse() function substantially. Instead of this:

   if (validate == true)
   {
       return true;
   }
   else
   {
       return false;
   }

All you need is this:

return validate;

Because the validate local variable is already a bool!

This removes the redundancy of checking a Boolean value against a Boolean constant (true), which prevents strange errors from creeping in and makes the code easier to read and understand.

In fact, you can use this general pattern any time you're working with Boolean values (bool). Rather than comparing them against the literal false or true, you can just write:

if (validate)  // test for truth
{
    // do whatever...
}

or

if (!validate)  // test for falsity
{
    // do whatever...
}