-1

A few months ago during an interview, I was asked how to go about implementing a boolean datatype in C. The two most common ways would to either be:

Preprocessor Macros:

#define BOOL unsigned char

Or typedefs:

typedef BOOL unsigned char;

So I was wondering what the exact benefits and trade-offs of using either preprocessor macros or typedefs are? I commonly find myself making datatypes like "uint16," (for unsigned shorts) and "ucharp," (for unsigned char pointers). Which would be best to use?

Thanks.

Benjamin
  • 1,223
  • 1
  • 13
  • 22

1 Answers1

2

The most natural answer is defining an enumerated type:

typedef enum {false = 0, true} BOOL;

It is important to note, however, that this BOOL type we have declared behaves a little bit differently than the C99 _Bool type (most commonly used through the bool macro defined in stdbool.h).

For example:

int main(void) {
    BOOL B;  // our type
    bool b;  // the type from C99

    B = -true; // -1
    b = -true; // 1

    B = true + true;  // 2
    b = true + true;  // 1

    return 0;
}

The C99 bool acts according to the rules of Boolean algebra, while our make-do BOOL acts just like a regular int. This is due to the fact that a variable of type enum is actually an int.

If you're using C99, there's absolutely no valid reason on this Earth to roll your own type rather than just use the bool defined in stdbool.h.

If you're on an earlier standard, a typedef'd enum is as good as it gets, unfortunately.

George Pîrlea
  • 385
  • 1
  • 4