Sunday 20 November 2011

What is the best way to represent true and false in C? in C programming

What is the best way to represent true and false in C?

In C, anything that evaluates to 0 is evaluated to be false, and anything that evaluates to a nonzero value is true. Therefore, the most common definition for false is 0, and the most common definition for true is 1. Many programs include header files that define this:

#define FALSE 0
#define TRUE 1

If you are writing a Windows program, you should note that this exact definition of TRUE and FALSE appears in the windows.h header file. This form of defining true and false is very common and perfectly acceptable. There are, however, a few other ways of defining true and false. For instance, consider this definition:

#define FALSE 0
#define TRUE !FALSE

This simply says that FALSE is 0 and TRUE is anything but 0. Note that even negative numbers, such as –1,
are nonzero and therefore evaluate to true. Another popular way to define true and false is to create your own enumerated type, such as Boolean (or BOOL), like this:

enum BOOL {
FALSE,
TRUE
};

As you might already know, the first element of an enumerated type is assigned the value 0 by default.Therefore, with the preceding enum definition, FALSE is assigned 0 and TRUE is assigned 1. Using an
enumerated type has some benefits over using the more common symbolic constant (#define). See FAQ V.6
and FAQ V.7 for an explanation of the benefit of using enum.

Which method is best? There is no single answer to this question. If you are writing a Windows program, TRUE and FALSE are already defined for you, so there is no need to create your own definition of TRUE and FALSE. Otherwise, you can choose your own way from the methods described previously.

Cross Reference:

V.6: What is the benefit of using enum to declare a constant?
V.7: What is the benefit of using an enum rather than a #define constant?

No comments:

Post a Comment