Data Types
Booleans
stdbool.h provides the bool, true, and false names for clear yes/no state.
stdbool
`#include <stdbool.h>` defines `bool`, `true`, and `false`.
ternary
The ternary operator chooses one of two values based on a condition.
Booleans
booleans.c
Replay: real traced execution (multi-file project)
#include <stdbool.h>
#include <stdio.h>
int main(void) {
bool enabled = true;
const char *label = enabled ? "enabled" : "disabled";
printf("flag=%s\n", label);
return 0;
}
#include <stdbool.h>
#include <stdio.h>
int main(void) {
bool enabled = false;
const char *label = enabled ? "enabled" : "disabled";
printf("flag=%s\n", label);
return 0;
}
enabled ← 1, label ← enabled
4int main(void) {5 bool enabled→ 1 = true; //@enabled=false6 const char *label→ enabled = enabled1 ? "enabled" : "disabled";78 printf("flag=%s\n", labelenabled);9 return 0;10}outputflag=enabled
enabled ← 0, label ← disabled
4int main(void) {5 bool enabled→ 0 = false;6 const char *label→ disabled = enabled0 ? "enabled" : "disabled";78 printf("flag=%s\n", labeldisabled);9 return 0;10}outputflag=disabled
Follow the Flag
enabledstarts astrue.- The ternary checks
enabled. - Because it is true,
labelbecomesenabled. - The program prints
flag=enabled. | enabled | label | output | | --- | --- | --- | | true | enabled |flag=enabled| | false | disabled |flag=disabled|
Exercise: booleans.c
Reproduce flag=enabled, then use enabled=false to predict the flag output.