Question

Traditionally, C did not have a Boolean defined until C99. Thus, searching headers files to know the optimized way of creating Boolean found are:

Windows.h [Microsoft C++]
---------
typedef int                 BOOL;

//false
#ifndef FALSE
    #define FALSE               0
#endif

//true
#ifndef TRUE
   #define TRUE                1
#endif

Defined in Tipo Booleano C

#if (__BORLANDC__ <= 0x460) || !defined(__cplusplus)
    typedef enum { false, true } bool;
#endif

Provided by c-faq.com section 9

typedef enum {false, true} bool;

In objc.h the bool is defined as:

typedef signed char     BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED

#define YES             (BOOL)1
#define NO              (BOOL)0

In reply to some question on stackoverflow.com

typedef enum { False = 0, True = 1 } Bool;
#define bool Bool
#define true True
#define false False

Which one is the optimized way?

Was it helpful?

Solution

If you use C89, I would go with the following definitions:

#define true 1
#define false 0
typedef unsigned char bool;

For memory reasons, _Bool is usually a 1-byte wide type. And in C99 _Bool is an unsigned type.

I personally don't like the definitions of bool as an enum as enum are implementation-defined types while the enum constant are always int.

Now if you want to favor speed over memory, you should consider using a type that matches the word size of your processor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top