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.
The value you return using the
returnstatement is literally returned whenever you call the function.So if you write this code somewhere else in your program:
then the
returnValuevariable will contain a Boolean value equivalent to whatever was returned by thetrueOrFalse()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
returnstatement correctly, but you can simplify your code in thetrueOrFalse()function substantially. Instead of this:All you need is this:
Because the
validatelocal variable is already abool!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 literalfalseortrue, you can just write:or