Monday, April 25, 2011

How do I cast a bool to a BOOL ?

Am I safe in casting a C++ bool to a Windows API BOOL via this construct

bool mybool = true;
BOOL apiboolean = mybool ? TRUE : FALSE;

I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears.

Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.

From stackoverflow
  • Do you mean

    
    bool b;
    ...
    BOOL apiboolean = b ? TRUE : FALSE;
    

    If so, then yes, this will work.

    Onorio Catenacci : Duh. Sorry--you're right of course. Thanks. I'll fix up my question.
  • Yes, that will work, but

    bool b;
    ...
    BOOL apiboolean = (BOOL) b;
    

    should work just as well, as does the reverse:

    bool bb = (bool) apiboolean;
    
    Dima : In that case, you should use static_cast(b).
    Greg Rogers : really you should just let it implicitly cast for you. The compiler knows how to cast between int's and bool's, and BOOL is usually a typedef for some int type.
    Dima : Greg, bool to int would probably work, but Visual Studio will give you a warning if you try to cast int to bool.
    Onorio Catenacci : Hi guys, yes, I'd considered all those ways of casting--I was only asking, as I said, because I thought there might be some subtle problem that I was missing. I think I prefer Dima's approach because what I'm doing is just more obvious (for the sake of anyone maintaining this code).
    Logan Capaldo : I use !! for int -> bool. Avoids the warning and less typing than static_cast. Course it looks a little silly.
    James Curran : @Logan: well, I object to using ! on an int (on principle). Also, while it's probably optimized to something sensible, the "straight" (non-optimized) translation of that is wicked.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.