A study session in this course is valid when it lasts from 1 through 180 minutes. That is two facts at once: the value is at least 1, and it is at most 180. Real rules are usually like this, a range or a combination, and writing them as a pile of nested if statements quickly becomes unreadable. C's logical operators join conditions into one expression that reads like the rule itself.
a && bis true when bothaandbare true.a || bis true when at least one of them is true.!ais true whenais false.
Like comparisons, each produces the int 1 or 0.
Predict and run
Is 181 valid? Predict the printed number.
#include <stdio.h>
int main(void) {
int minutes = 181;
int valid = minutes >= 1 && minutes <= 180;
printf("Valid: %d\n", valid);
return 0;
}Check your prediction
Valid: 0181 passes the first comparison but fails the second, and && needs both. Try 0, 1, 180 and 181. Only the two middle values print 1. Those four values are exactly the ones worth testing for any range: each endpoint and the first value outside it.
Two ways to say the same rule
"Accept when inside" and "reject when outside" are the same rule seen from both sides. !(minutes >= 1 && minutes <= 180) means the same as minutes > 180 || 1 > minutes, which you would normally write with the smaller value first: minutes < 1 || minutes > 180. Notice that negating the rule flips every comparison and swaps && for ||. Swapping only one of them is a classic bug:
#include <stdio.h>
int main(void) {
int minutes = 9000;
int inside = minutes >= 1 && minutes <= 180;
int outside = minutes < 1 || minutes > 180;
printf("%d %d %d\n", inside, outside, (!inside) == outside);
return 0;
}0 1 1The last number checks the claim: (!inside) == outside is 1, and it stays 1 for any value you try. Now look at a version that flips the comparisons but forgets to swap the operator:
int broken = minutes >= 1 || minutes <= 180;It looks reasonable, but it is true for every integer: any number is either at least 1 or at most 180, so it would accept -40 and 9000. Clang notices and reports:
error: overlapping comparisons always evaluate to true [-Wtautological-overlap-compare]Not every logic slip is this easy for a compiler to spot, so the habit that protects you is testing: a value far outside the range, such as 9000, exposes a condition that accepts everything.
Why the mathematical form is wrong
In mathematics you might write 1 <= minutes <= 180. C accepts that text, but it means something else. It evaluates left to right: the first comparison becomes 0 or 1, and then that 0 or 1 is compared with 180.
int minutes = 500;
if (1 <= minutes <= 180) {
printf("Valid\n");
}For 500, the first comparison gives 1, and comparing that 1 with 180 also gives 1, so this prints Valid. In fact it is true for every value. Compilers often warn that a comparison result is being compared again. Always write a range as two comparisons joined by &&.
Short-circuit evaluation
&& and || evaluate their left side first and only evaluate the right side when it can still change the answer. If the left side of && is false, the whole result is already false, so the right side never runs. If the left side of || is true, the right side is skipped. This is a guarantee, not an optimization, and C programs rely on it to put a safety check first:
#include <stdio.h>
int main(void) {
int sessions = 0;
int total = 0;
if (sessions != 0 && total / sessions >= 25) {
printf("Long average\n");
} else {
printf("No long average\n");
}
return 0;
}No long averageBecause sessions != 0 is false, the division never runs, so the program never divides by zero. Swap the two sides and the division would run first, which is undefined behavior. Set sessions to 2 and total to 60 and the message changes to Long average, because now the left side is true and the right side is evaluated: 60 / 2 is 30.
Short-circuiting also means the right side may not run at all, so never hide work that must always happen, such as updating a counter, on the right of && or ||. Put that work in its own statement, and keep conditions as pure questions. On Day 5 you will use the same pattern to check that a pointer is valid before following it.
Practice
Your turn
A session is worth reviewing when its duration is valid (1 through 180) and either it lasted at least 60 minutes or it was rated below 3. Write review as a single expression, then print it with the minutes and rating. The starter sets minutes to 45 and rating to 2, and should print:
45 min, rating 2: review 1Then predict and check these pairs: 45 and 4 (0), 60 and 5 (1), 200 and 1 (0), 0 and 1 (0).
#include <stdio.h>
int main(void) {
int minutes = 45;
int rating = 2;
// Write your solution here.
return 0;
}Hint 1: the idea
Write the two parts separately in words: "valid" and "long or poorly rated". Join them with &&. The second part needs ||, and it needs parentheses so it is treated as one unit.
Hint 2: a first step
Start with int valid = minutes >= 1 && minutes <= 180; and print it. Then build review from valid and the parenthesized || part.
Show one solution
#include <stdio.h>
int main(void) {
int minutes = 45;
int rating = 2;
int review = minutes >= 1 && minutes <= 180 && (minutes >= 60 || rating < 3);
printf("%d min, rating %d: review %d\n", minutes, rating, review);
return 0;
}45 min, rating 2: review 1&& binds more tightly than ||, so without the parentheses the expression would mean "valid and long, or poorly rated", and 200 minutes with rating 1 would be flagged even though the duration is invalid. The parentheses make the rule read as it was written. Next you will repeat work with loops, which is where these conditions decide when to stop.
Completion is saved in this browser only. It does not measure mastery.