Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple boolean question (Beginner)

Status
Not open for further replies.

Delameko

Programmer
Oct 14, 2003
37
GB
I've got a boolean value being returned from a class, and I'm trying to create an if statement, something like:

if (boolean == true)
cout << &quot;True!&quot;;
else
cout << &quot;False!&quot;;

Well its not working as it always finds it true.

This is because the boolean == true is an int comparison, right?

So can someone help me out? All the text's I see only mention booleans in passing...

Thanks in advance.
 
I think it would be best to put the output statement in the member function itself like so if it is possible:

BOOL SomeFN(param a, param b)
{
if (a == b)
{
cout << &quot;True!&quot;;
return TRUE;
}
if (a != b)
{
cout << &quot;False!&quot;;
return FALSE;
}
}



-Bones
 
I don't think
boolean == true
is valid on all compilers... a boolean variable is usually just an int, but the &quot;true&quot; reserved keyword is special.

Try the following:

if (boolean)
cout << &quot;True!&quot;;
else
cout << &quot;False!&quot;;

(you can also do
if( !boolean )
if you want to trigger on boolean == false)

Do not forget that
if( boolean )
will fire on ANY non-zero value of boolean! Make sure it is properly initialized!

Vincent
 
The
Code:
bool
type is a standard C++ type. Anything else, like BOOL, is not and is usually just a typedef for an int or something. If you want to use the actual
Code:
bool
type, it can only have two values -
Code:
true
and
Code:
false
. You might be able to convert an int (or BOOL) to a
Code:
bool
with just a warning, but if you stick to
Code:
bool
your comparisons (like below) will work.

Code:
bool myBooleanVariable = true;

if (myBooleanVariable == true)
    cout << &quot;True!&quot;;
else
    cout << &quot;False!&quot;;

if (myBooleanVariable)
    cout << &quot;True!&quot;;
else
    cout << &quot;False!&quot;;

if (myBooleanVariable == false)
    cout << &quot;False!&quot;;
else
    cout << &quot;True!&quot;;

if (!myBooleanVariable)
    cout << &quot;False!&quot;;
else
    cout << &quot;True!&quot;;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top