Alex Rivera | Logout

When should BOOL and bool be used in C++?

Asked 2009-05-06T15:06:21.780
23

When should BOOL and bool be used in C++ and why?

I think using bool is cleaner and more portable because it's a built-in type. But BOOL is unavoidable when you interactive with legacy code/C code, or doing inter-op from .NET with C code/Windows API.

So my policy is: Use bool inside C++. Use BOOL when talk to outer world, e.g., export function in windows DLL.

Is there a definitive explanation of when to use one over the other?

Edit
Report

2 Answers

12

If BOOL is some sort of integral type, and it always is, and BOOL is defined so that it works right, the standard conversions will automatically get it right. You can't quite use them interchangeably, but you can get close.

Use BOOL at the interface, where you have to talk to the Win32 API or whatever. Use bool everywhere else.

answered 2009-05-06T19:46:07.020
2

Another situation where you should use BOOL: when implementing a callback function that takes or returns a BOOL.

For example, EnumWindows() takes a pointer to a callback function with the following signature:

BOOL CALLBACK EnumWindowsProc(      
    HWND hwnd,
    LPARAM lParam
);

If you use bool for this, you will have to typecast your function pointer.

answered 2009-05-06T19:09:34.393

Your Answer