Coding Techniques
C Loops · Study material
Sentinel-controlled loops
When you do not know how many values will come, read until a special "sentinel" value (or until input fails). Testing the result of scanf() also stops cleanly on bad input or end of file.
#include <stdio.h>
int main(void) {
int x, sum = 0, count = 0;
while (scanf("%d", &x) == 1 && x != -1) { /* stop at bad input or the sentinel -1 */
sum += x;
count++;
}
printf("%d numbers, sum %d\n", count, sum);
return 0;
}
12 7 30 -1 99
3 numbers, sum 49
Leaving nested loops in one step
break only leaves the inner loop. A single forward goto to a label after the loops is the clearest way out – or move the search into a function and return.
#include <stdio.h>
int main(void) {
int grid[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int target = 6, row = -1, col = -1;
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++)
if (grid[r][c] == target) {
row = r;
col = c;
goto found; /* leaves both loops at once */
}
found:
if (row >= 0)
printf("found %d at row %d, column %d\n", target, row, col);
else
printf("%d not found\n", target);
return 0;
}
found 6 at row 1, column 2
Move invariant work out of the loop
Anything that gives the same result on every pass – strlen(s), a size, a square root – belongs before the loop. for (i = 0; i < strlen(s); i++) rescans the string on every pass and turns O(n) into O(n²).
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s = "loop invariant code motion";
size_t n = strlen(s); /* computed once, not on every pass */
int spaces = 0;
for (size_t i = 0; i < n; i++)
if (s[i] == ' ')
spaces++;
printf("%d spaces in %zu characters\n", spaces, n);
return 0;
}
3 spaces in 26 characters
The do { … } while (0) macro idiom
A multi-statement macro wrapped in do { … } while (0) behaves like one statement, so it works after an if without braces and requires a semicolon.
#define SWAP(a, b) do { int tmp_ = (a); (a) = (b); (b) = tmp_; } while (0)
if (x > y)
SWAP(x, y); /* expands safely, even with an else after it */
else
puts("already in order"); Good loop habits
- Declare the counter in the
forheader so it cannot leak. - Loop with
i < n; usesize_tfor sizes and indexes fromsizeof/strlen. - Count down with
for (size_t i = n; i-- > 0; ). - Use an integer counter, never a
float/doubleone. - Always use braces when the body is more than one line.
- Make sure every
whilechanges something its condition tests.