Using boolean data-types with ANSI-C
Author: Jean-David Gadina <macmade(at)eosgarden.com>
Copyright (C) Jean-David Gadina.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled GNU Free Documentation License.
Boolean data types are certainly the most often used data-type in any programming language.
They are the root of any programming logic.
Nowadays, few people remember that the boolean data type wasn't defined with the ANSI (C89) C programming language.
They are the root of any programming logic.
Nowadays, few people remember that the boolean data type wasn't defined with the ANSI (C89) C programming language.
It was added as part of the ISO-C99 standard, with the «stdbool.h» header file.
Before this, it was up to each programmer to define its own boolean type, usually an enum, like the following one:
typedef enum { false = 0, true = 1 } bool;
Of course, unless using prefixes, such declarations may cause many problems, especially when using libraries, in which each programmer defined a boolean datatype.
You'll then get linking problems, because of duplicates symbols.
The ISO-C99 specification defined a «bool» datatype, defined in the «stdbool.h» header file.
That's great, but how can we be sure that we are coding for C99, what about code portability with old systems?
The best way to ensure backward compatibility is to declare the boolean data-type exactly the same way C99 does.
A macro, named «__bool_true_false_are_defined» is specified, so you can know if the boolean data-type is actually declared and available.
No surprise, the «true» value must be defined to 1, and «false» to 0.
In C99, the «bool» data-type must expand to «_Bool». If it's not defined, you can rely on on other data-type, like «char», that will save a few bits compared to integers.
The final declaration may look like this, to ensure a maximum portability and compatibility:
#ifndef __bool_true_false_are_defined #ifdef _Bool #define bool _Bool #else #define bool char #endif #define true 1 #define false 0 #define __bool_true_false_are_defined 1#endif





Comments:
Add a comment: