44 lines
938 B
Markdown
44 lines
938 B
Markdown
---
|
|
tags:
|
|
- C
|
|
---
|
|
|
|
Booleans are a bit weird in C. _Oficially_ they don't exist as a core primitive
|
|
data type. Instead you use integers on the basis that:
|
|
|
|
> `0` is false and any non-zero value is true (but typically indicated with `1`)
|
|
|
|
Hence why the `int main()` [entrypoint](./Entry_point_to_C_programs.md) returns
|
|
`int`, because "success" is `1` and "error" is `0`.
|
|
|
|
A common example of this approach:
|
|
|
|
```c
|
|
|
|
int is_running = 1; // true
|
|
int has_error = 0; // false
|
|
|
|
if (is_running) {
|
|
// Do stuff
|
|
}
|
|
|
|
```
|
|
|
|
Since the **C99** standard, a dedicated Boolean type has been available.
|
|
|
|
```c
|
|
#include <stdbool.h>
|
|
|
|
bool is_running = true;
|
|
bool has_error = false;
|
|
|
|
if (is_running) {
|
|
// Do stuff
|
|
}
|
|
```
|
|
|
|
Note, you must include the bool header file which is part of the core in order
|
|
to have access to the `bool`, `true`, and `false` keywords.
|
|
|
|
This is just syntactic sugar though, and underneath it is just `int` values for
|
|
`0` and `1`.
|