TRUE or true

Started by
4 comments, last by SiCrane 16 years, 3 months ago
I've been noticing in articles and tutorials that TRUE and FALSE get used a lot. I know they are just a define in windef.h to 0 and 1, but why use these instead of the regular bool? Should i be aware when to use which? i.e check to see if a paramater or variable is of the type 'BOOL' (typedef int) rather than 'bool'. Some insight would be appreciated. [Edited by - JimmyDeemo on January 28, 2008 5:42:13 AM]
Advertisement
(Argh... That's the second time today I've lost a post)

The WINAPI is a C API. C90 didn't have a proper Boolean type, and so had to rely on typedefs and macros to imitate one.

As for conversion, BOOL will safely, and implicitly, convert to bool (0 is false, non-zero is true for conversion of integral values[1] to bool. I don't know about the other way; I strongly suspect it's implementation-defined (I think it'll work for false, but that the implementation is free to pick any non-zero value for true).

1. I think bool might technically be a integral type itself, but I can't remember and I think it's clear what I mean.
[TheUnbeliever]
When you work with C++ (which has a boolean datatype, called bool), you should use bool. That's what it's for.

If you're working in C, which doesn't have a boolean datatype (Or at least, didn't. Not sure about C99), you have to use something else. Such as a typedef.

And when you're working with the Win32 API, you have to accept that they use BOOL typedefs (because they have to be compatible with C)

But in your own code (assuming you're writing C++) you should definitely use bools.
I beleave bool is like an int tested != 0 at every assignment to force 0/1 value.

In visual studio sizeof(bool) is 1, while for gcc sizeof(bool) is 4. 31 padding bit (should) grant compatibility with #define true 1.
This difference may generate some trouble on file IO; Try to avoid things like Read(Buffer, sizeof(bool)), because if the file has been saved using Write(Buffer, mybool, sizeof(bool)) on a different system, the program may lead to unexpected behaviour. Always convert to char avoids this problem.
Quote:Original post by Spoonbender
When you work with C++ (which has a boolean datatype, called bool), you should use bool. That's what it's for.

If you're working in C, which doesn't have a boolean datatype (Or at least, didn't. Not sure about C99), you have to use something else. Such as a typedef.

And when you're working with the Win32 API, you have to accept that they use BOOL typedefs (because they have to be compatible with C)

But in your own code (assuming you're writing C++) you should definitely use bools.


Thanks for the clarification. Also cheers for the tip Nyarlath.

C99 has the _Bool type, which is approximately equivalent to the C++ bool type. If you include stdbool.h macros define bool, true and false.

This topic is closed to new replies.

Advertisement