views:

804

answers:

2

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.

+8  A: 

Do you mean


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

If so, then yes, this will work.

Dima
Duh. Sorry--you're right of course. Thanks. I'll fix up my question.
Onorio Catenacci
+3  A: 

Yes, that will work, but

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

should work just as well, as does the reverse:

bool bb = (bool) apiboolean;
James Curran
In that case, you should use static_cast<BOOL>(b).
Dima
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.
Greg Rogers
Greg, bool to int would probably work, but Visual Studio will give you a warning if you try to cast int to bool.
Dima
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).
Onorio Catenacci
I use !! for int -> bool. Avoids the warning and less typing than static_cast. Course it looks a little silly.
Logan Capaldo
@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.
James Curran