Boolean values
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Classic C has no separate boolean type: 0 is false, anything else is true. Comparisons return an int: 1 or 0.
printf("%d\n", 5 > 3); // 1
printf("%d\n", 5 == 3); // 0
if (42) { ... } // runs: 42 ≠ 0
Since C99 there's the <stdbool.h> header with the bool type and the words true / false. They're just convenient names for 1 and 0:
#include <stdbool.h>
bool done = false;
Logical operators are lazy (short-circuit): if the result is clear from the left side, the right side isn't evaluated. This is used as a safeguard:
if (count != 0 && total / count > 10) { ... } // there will be no division by zero
A classic mistake is = instead of ==:
if (x = 5) // assignment! Always true, and x is now 5
With the -Wall flag, the compiler warns you about it.
Task. Read a year and print 1 if it's a leap year, otherwise 0. A year is a leap year if it's divisible by 4 and not divisible by 100, or if it's divisible by 400. Write a single boolean expression without if.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.