Simulate boolean type in C

Asked

Viewed 2,417 times

8

What is the most appropriate way to simulate the type bool in C? My teacher did it in a very simple way.

#define bool int

But I also found an excellent answer here (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 statement and where they can cause me headache in the future if I implement them in a library?

1 answer

7


The best option is this:

#include <stdbool.h>

This requires a C99 compliant compiler, which is virtually all counting, you can use the type _Bool. If you don’t have a compiler like this, the same as the default:

#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

Source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.