Decisions and loops
Choosing with if and switch, repeating with while and for, and the loop that never ends.
Making decisions with if
So far every statement has run, in order. An if statement runs a block of code only when a condition is true.
#include <stdio.h>
int main(void) {
int temperature = 85;
if (temperature > 80) {
printf("Too hot. Switching the heater off.\n");
}
printf("Done.\n");
return 0;
}
Change 85 to 60 and run it again. The first message disappears, and the second still prints, because it sits outside the braces.
Add else to say what should happen otherwise.
#include <stdio.h>
int main(void) {
int button_pressed = 0;
if (button_pressed) {
printf("LED on\n");
} else {
printf("LED off\n");
}
return 0;
}
A condition is true when it is not zero. That is why a variable holding 1 or 0 can be used directly as a condition.
More than two choices
Chain conditions with else if. They are tried from the top, and only the first one that is true runs.
#include <stdio.h>
int main(void) {
int battery = 35;
if (battery > 60) {
printf("green\n");
} else if (battery > 20) {
printf("yellow\n");
} else {
printf("red\n");
}
return 0;
}
Pitfall: A semicolon straight after the parentheses, as in
if (x > 5);, ends theifthere and then. The block that follows always runs.
Choosing between fixed values with switch
When one value is compared against many fixed possibilities, switch is tidier than a long chain.
#include <stdio.h>
int main(void) {
int command = 2;
switch (command) {
case 1:
printf("start\n");
break;
case 2:
printf("stop\n");
break;
default:
printf("unknown command\n");
break;
}
return 0;
}
Execution jumps to the matching case and runs downwards until it meets a break. If you leave the break out, it carries straight on into the next case. default handles every value that has no case of its own, and you should always include it.
Repeating with while
A loop repeats a block of code. A while loop keeps going as long as its condition is true, and it checks before every pass.
#include <stdio.h>
int main(void) {
int count = 3;
while (count > 0) {
printf("%d\n", count);
count--;
}
printf("liftoff\n");
return 0;
}
Something inside the loop must eventually make the condition false. If you forget count--, the loop never ends. Try removing it and running the example. The simulator stops a runaway program and tells you so, where a real board would simply hang.
Counting with for
Most loops count. A for loop puts the three parts of counting on one line.
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; i++) {
printf("i is %d\n", i);
}
return 0;
}
| Part | In the example | When it runs |
|---|---|---|
| Start | int i = 0 | Once, before the loop begins |
| Condition | i < 5 | Before every pass. The loop ends when it is false |
| Step | i++ | After every pass |
The loop above runs with i equal to 0, 1, 2, 3 and 4. That is five passes. Starting from 0 and continuing while i < n is the standard C loop, and it runs exactly n times.
Here a loop adds up the numbers from 1 to 10, keeping a running total in a variable declared before the loop.
#include <stdio.h>
int main(void) {
int total = 0;
for (int i = 1; i <= 10; i++) {
total += i;
}
printf("total = %d\n", total);
return 0;
}
do ... while
A do ... while loop checks its condition after each pass, so the body always runs at least once.
do {
reading = read_sensor();
} while (reading == 0); // try again until we get a real reading
| Loop | Use it when |
|---|---|
for | You know how many times to repeat |
while | You repeat until something happens, possibly zero times |
do ... while | The body must run at least once |
Leaving a loop early
break leaves the loop at once. continue skips the rest of the current pass and goes on to the next one.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
if (i > 7) {
break; // stop completely
}
printf("%d ", i);
}
printf("\n");
return 0;
}
The loop that never ends
On a desktop, a program finishes and returns to the operating system. A microcontroller has nothing to return to. Its program sets things up once and then repeats the same work for as long as there is power.
int main(void) {
setup_hardware();
while (1) { // 1 is always true, so this never ends
read_buttons();
update_display();
}
}
This is called the main loop or super-loop, and nearly every firmware project is built around one.
Common mistakes
if (x = 5)instead ofif (x == 5). The first stores 5 and is always true.- A semicolon after
if (...)orwhile (...). - A loop that runs one time too many or too few. Check the first and last values.
- Forgetting to change the loop variable, so the loop never ends.
- Forgetting
breakin aswitch.
Interview question: Why does almost every embedded program contain while (1)?
Answer: A microcontroller has no operating system to return to, so main must never finish. The program initialises the hardware once and then repeats its work forever in a main loop, reading inputs, updating state and driving outputs. If main did return, the chip would run into whatever code follows it, which is usually a trap that simply halts.
In the product: a washing machine
A wash programme is decisions and loops: fill until the level switch trips, wash for a while, and stop at once if the door is opened. Here is the fill step, written as a loop with a safety check inside it.
#include <stdio.h>
int main(void) {
int level = 0; // water level, in percent
int door_open = 0;
int target = 60;
while (level < target) {
if (door_open) {
printf("door opened: stop filling\n");
break;
}
level += 15; // the valve adds water each second
printf("filling... %d%%\n", level);
if (level == 45) door_open = 0; // try changing this to 1
}
if (level >= target) printf("full: start washing\n");
return 0;
}
Build it: what the display should say
This is step 3 of the module project. A real scale does not just print a number: it warns when the load is too heavy, shows a dash for a negative reading, and counts down when it switches itself off.
Lab: Decide what to show, and count down
display_text(grams)prints one line, chosen like this:- above 5000 g:
OVERLOAD(the scale's limit is 5 kg), - below 0:
----(something was lifted off after taring), - otherwise the weight, such as
125 g. auto_off(seconds)prints the countdown the scale shows before switching off:Off in 3,Off in 2,Off in 1, one per line, fromsecondsdown to 1, thenBye. With 0 seconds it prints onlyBye.
Going deeper
Interview question: How would you structure a washing machine's programme so a new wash cycle can be added without rewriting the controller?
Answer: Describe each cycle as data: a list of steps (fill to a level, agitate for a time at a speed, drain, spin), and write one engine that runs any list. Safety checks such as the door lock, overfill and an unbalanced drum run on every pass whatever the step, and a state machine handles pause, resume and errors. A new cycle is then a new table, which can even be updated in the field.
Interview question: Why must every case in a switch usually end with break?
Answer: Without break, execution falls through into the next case and runs its statements too, which is almost never intended. Fall-through can be useful deliberately, for example several case labels sharing one block, but intentional fall-through between statements should be marked with a comment or the fallthrough attribute so readers and compilers know it is not a bug. A default case should handle unexpected values.
Interview question: What is the difference between while and do ... while?
Answer: A while loop tests its condition before each iteration, so the body may run zero times. A do-while loop runs the body first and tests afterwards, so it always runs at least once. do-while suits cases like reading input until it is valid; it is also used in the do { ... } while (0) macro idiom to make several statements behave as one.
Explain it: In your own words, explain why for (;;) is common in firmware and how such a program still does more than one thing.
Answer: for (;;) is a loop with no condition, so it runs forever, which is what firmware needs because there is nothing to return to. It does several things by never waiting inside the loop: each pass quickly checks each activity, such as whether a button changed or a timer period elapsed, does a small amount of work if needed and moves on. Interrupts handle urgent events, and the loop handles everything else in turn, many times per second.