Simulate the Boolean type in C

7

What is the most appropriate way to simulate type bool in C? My teacher did it quite simply.

#define bool int

But I also found an excellent answer aqui ( follows a copy of the code).

// Criando a enumeração:
enum boolean {
    true = 1, false = 0
};
// Permitindo a sua declaração como um tipo qualquer:
typedef  enum boolean  bool;

// Agora podemos escrever e compilar os códigos como:
int main () {

    bool b = true;
    if (b) {
        b = false;
    }

    return 0;
}

What are the pros and cons of both types of claims and where can they cause me a headache in the future if I implement them in a library?

    
asked by anonymous 01.11.2015 / 15:48

1 answer

6

The best option is this:

#include <stdbool.h>

This requires a C99-compliant compiler, which virtually all count. You can use type _Bool . If you do not have a compiler like this, the same as the default does:

#define bool _Bool
#define true 1
#define false 0
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Define _Bool, bool, false, true as a GNU extension. */
#define _Bool bool
#define bool  bool
#define false false
#define true  true
#endif

Font .

    
01.11.2015 / 16:04