Section A.6 Conditions and Loops
The listings below show the same few lines in Python, on the left, and in C, on the right.
done = False
late = False
count = 0
while count < 10:
count += 1
total = 0
for i in range(5):
total = total + i
if count == 10 and not done:
done = True
elif total > 20 or late:
done = False
else:
count = 0
int done = 0;
int late = 0;
int count = 0;
while (count < 10) {
count++;
}
int total = 0;
for (int i = 0; i < 5; i++) {
total = total + i;
}
if (count == 10 && !done) {
done = 1;
} else if (total > 20 || late) {
done = 0;
} else {
count = 0;
}
Conditions. A condition goes in parentheses and the statements it controls go in braces.
elif is written
else if, and
and,
or and
not are written
&&,
|| and
!. The single
& and
| are different operators, which work on individual bits; they are taught in
Subsection 1.2.3.
True and false. In this course we use integers for true and false: 0 is evaluated as false in C, and any other integer value is evaluated as true. That is why
while (1), the loop in which every program in this book repeats its work, runs forever. It is the C equivalent of Python’s
while True:.
++ and --. count++ adds 1 to
count, the same as
count += 1, and
count-- subtracts 1. The compound assignments
+=,
-= and
*= work as they do in Python, and
/= divides the way
/ does in C. C has no power operator:
2 ** 3 does not compile, and
2 ^ 3 compiles, but
^ is a bit operator rather than a power, and the value is 1.
The for loop. A C
for loop has three parts, separated by semicolons. For example, in the loop
for (int i = 0; i < 5; i++), the first part,
int i = 0, is the initialization and runs once, before the loop starts. The second part,
i < 5, is the condition: it is checked before every pass, and the loop ends as soon as it is false. The third part,
i++, runs after every pass. So this loop runs its body with
i equal to 0, 1, 2, 3 and 4, exactly like Python’s
for i in range(5):.
= and ==. = assigns and
== compares, as in Python. The difference is that an assignment inside an
if is a syntax error in Python but legal in C.
if (count = 10) stores 10 in
count and then tests the value 10, which is true, so its body runs every time. At most, the compiler issues a warning.
Optional braces. Loops and
if statements that control only a single statement need not have it enclosed in braces. Only that one statement is controlled, no matter how the lines below it are indented:
if (count == 10)
done = 1;
count = 0; // indented, but not controlled by the if
Those lines are therefore equivalent to the following:
if (count == 10) {
done = 1;
}
count = 0;
Always use braces in your own code, even around a single statement.
The empty statement. A semicolon on its own is a complete statement that does nothing, and it can be the whole body of a loop. Blinky’s delay loop is built this way:
for (int i = 0; i < 100000; i++);
The body of that loop is the final semicolon, so the loop counts
i from 0 to 100000 and does nothing else, and counting that far takes time. Typed by accident after an
if, the same semicolon becomes the whole body of the
if, and the block after it is not part of the conditional execution but rather runs regardless of the outcome of the condition:
if (count > 100); // the if ends at this semicolon
{
count = 0; // so this block runs every time
}
switch. A
switch compares one integer value against a list of constants. It is a compact form of an
if and
else if chain that tests the same variable each time. Execution jumps to the matching
case label and continues until it reaches a
break or the end of the
switch. Without a
break, execution continues into the statements of the next case, which is called
fall-through. The statements after
default run when no case matches, like a final
else.
The constants in a
switch are often given names with
typedef enum, as in the listing below. The line
typedef enum {IDLE, RUNNING} state_t; defines a new type,
state_t, whose values are the names
IDLE and
RUNNING; C gives them the values 0 and 1.
typedef enum {IDLE, RUNNING} state_t; // IDLE is 0, RUNNING is 1
state_t state = IDLE;
switch (state) {
case IDLE:
count = 0;
break;
case RUNNING:
count = count + 1;
break;
default:
count = 100;
break;
}
Check Your Understanding Check Your Understanding
1.
What value does
total hold after these lines run?
int total = 0;
for (int i = 0; i < 4; i++);
total = total + 1;
-
1
-
Correct. The semicolon at the end of the for line is the loop’s whole body, so the loop runs four times doing nothing. The indented line is not part of the loop, and runs once afterwards.
-
4
-
That would be true without the semicolon at the end of the for line. With it, the loop body is empty, and the indentation of the next line makes no difference in C.
-
0
-
The line total = total + 1; does run, once, after the loop has finished.
-
3
-
The loop runs with i equal to 0, 1, 2 and 3, but its body is the empty statement, so none of those passes changes total.
2.
What values do
x and
y hold after these lines run?
int x = 5;
int y;
if (x = 0) {
y = 1;
} else {
y = 2;
}
-
x is 0 and y is 2.
-
Correct. x = 0 is an assignment, not a comparison: it stores 0 in x, and the value it tests is 0, which is false, so the else branch runs.
-
x is 5 and y is 2.
-
This is what x == 0 would do. A single = assigns, so x is changed to 0.
-
x is 0 and y is 1.
-
The assignment happens, but the condition then tests the value that was assigned, 0, which is false.
-
The program does not compile.
-
An assignment inside a condition is a syntax error in Python but legal in C. At most, the compiler issues a warning.