char and bool
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.
The shortcut
Letters are numbers, and truth is 0 or 1. Whenever a char or bool looks puzzling, replace it by the integer it really holds and redo the sum.
Read the unit
The character after
=is'C'. Store it:char unit = 'C';, which holds 67.
Drills
Answer fast — trust the rule.
On an ASCII system, what does char unit = 'C'; printf("%d\n", unit); print?
What is the value of '7' - '0'?
What does bool b = 42; printf("%d\n", b); print?
What is sizeof(char)?
Is plain char signed or unsigned?
Remember
- char is a tiny integer holding a character code; bool holds 0 or 1, nothing else.
- Shortcut: swap in the integer the value really holds;
c - '0'turns a digit character into its number. - Trap: nonzero becomes 1 in a
bool, and plaincharmay be signed or unsigned.
