char and bool
A char is a one-byte integer that holds a character code and a bool holds only 0 or 1, so both take part in arithmetic like any other integer.
Distinguish character codes, text sequences and boolean conditions.
The logger's settings file says unit=C, and a switch on the board reports whether the vents are open. One is a letter and the other is a yes-or-no, yet in C both are stored as small integers. Seeing them that way makes a surprising amount of C suddenly obvious.
The rule
char is a tiny integer; bool holds 0 or 1, nothing else.
char is one byte, and sizeof(char) is 1 by definition. It stores a character's code, not a picture of the letter. On ASCII-based systems, which is nearly all of them, 'C' is 67 and '0' is 48.
char unit = 'C';
printf("%c %d\n", unit, unit); /* prints: C 67 */Things worth knowing about char:
- A character constant such as
'C'actually has typeintin C. It is a number you can do arithmetic with. - The standard guarantees that the digits
'0'to'9'have consecutive codes, so'7' - '0'is exactly 7 on every system. Letters have no such guarantee, though they are consecutive in ASCII. - Whether plain
charis signed or unsigned is implementation-defined. For raw bytes, say which you mean:unsigned charoruint8_t. - Escapes write the hard-to-type characters:
'\n'newline,'\t'tab,'\0'the zero byte that ends every string,'\''a single quote.
bool arrived in C99 as _Bool. Include <stdbool.h> to get the friendly names bool, true and false. (C23 makes all three built-in keywords, so the header is no longer required there.)
#include <stdbool.h>
bool vents_open = false;
bool is_celsius = (unit == 'C'); /* a comparison gives 1 or 0 */A bool can only hold 0 or 1. Converting any nonzero value to bool gives 1; zero gives 0. So bool b = 42; stores 1. In conditions, C still accepts any number: zero is false and everything else is true.