Why does the WinAPI use an int (32 bits) for the BOOL type?

boolean, c++, int, winapi, windows

Solution

Wow, slow down a little bit there. First of all, I'm pretty sure programmers have been using 4-byte `int`s for boolean variables since the beginning of programming on x86. (There used to be no such thing as a `bool` datatype). And I'd venture to guess that this same typedef is in the Windows 3.1 `<Windows.h>`.

Second, you need to understand a bit more about the architecture. You have a 32-bit machine, which means that all of the CPU registers are 4-bytes or 32-bits wide. So for most memory accesses, it is more efficient to store and access 4-byte values than it is for a 1-byte value.

If you have four 1-byte boolean variables packed into one 4-byte chunk of memory, three of those are not DWORD (4-byte) aligned. This means the CPU / memory controller actually has to do more work to get the value.

And before you go smashing on MS for making that "wasteful" typedef. Consider this: Under the hood, most compilers (probabily) still implement the `bool` datatype as a 4-byte `int` for the same reasons I just mentioned. Try it in gcc, and take a look at the map file. I bet I am right.

Problem

``` // <windef.h> typedef int BOOL; ``` Isn't this a waste of memory since an int is 32 bits? Just in case I was wrong, I tried sending a normal `bool*` to a function that required `BOOL*` and didn't work until I used the typedef int.

Original source

Related problems