4

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.

James Curran
  • 101,701
  • 37
  • 181
  • 258
Onorio Catenacci
  • 14,928
  • 14
  • 81
  • 132

3 Answers3

10

Do you mean


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

If so, then yes, this will work.

Dima
  • 38,860
  • 14
  • 75
  • 115
3

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
  • 101,701
  • 37
  • 181
  • 258
  • In that case, you should use static_cast(b). – Dima Nov 05 '08 at 20:25
  • 1
    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 Nov 05 '08 at 20:39
  • 1
    Greg, bool to int would probably work, but Visual Studio will give you a warning if you try to cast int to bool. – Dima Nov 05 '08 at 20:57
  • 1
    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 Nov 06 '08 at 14:28
  • I use !! for int -> bool. Avoids the warning and less typing than static_cast. Course it looks a little silly. – Logan Capaldo Mar 04 '09 at 01:43
  • @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 Mar 04 '09 at 14:30
1

Visual Studio 2005 will simply accept:

bool b = true;
BOOL apiboolean = b;

no casting required.

Note that the other way round BOOL->bool does not simply work like this.

Onorio Catenacci
  • 14,928
  • 14
  • 81
  • 132
Martin Ba
  • 37,187
  • 33
  • 183
  • 337