ZetCode

K&R C control flow

last modified December 5, 2026 K&R C 1978

The control-flow statements of C have kept their form since 1978: if and else, while, for, do, switch, break, continue, and goto. This article shows them as K&R programs use them, with integer conditions and with all declarations at the start of a block. The if else, for loop, switch, break and continue tutorials cover the shared syntax in more depth.

Conditions are integers

The condition of an if statement is any expression in parentheses. If its value is nonzero, the statement after the condition runs; otherwise the statement after else runs, if there is one. Since there is no boolean type, K&R programs often test a number directly.

conditions.c
#include <stdio.h>

int main()
{
    int n, count;

    n = 14;
    count = 0;

    if (n % 2)
        printf("%d is odd\n", n);
    else
        printf("%d is even\n", n);

    if (count)
        printf("count is %d\n", count);
    else
        printf("count is zero\n");

    if (n & 4)
        printf("bit 2 of %d is set\n", n);
    return 0;
}

if (n % 2) is true when the remainder is 1, so the test reads "if n is odd". if (count) means if (count != 0), and if (n & 4) tests a single bit. A branch holds one statement; several statements are grouped into one with braces.

$ gcc -std=c89 -pedantic -Wall -Wextra -o conditions conditions.c
$ ./conditions
14 is even
count is zero
bit 2 of 14 is set

else if

A multi-way decision is written as a chain of if and else statements. The conditions are tested in order, and only the first branch whose condition is true runs. The final else catches the cases that no condition matched.

grades.c
#include <stdio.h>

int main()
{
    int score;
    char grade;

    score = 73;

    if (score >= 90)
        grade = 'A';
    else if (score >= 80)
        grade = 'B';
    else if (score >= 70)
        grade = 'C';
    else if (score >= 60)
        grade = 'D';
    else
        grade = 'F';

    printf("score %d, grade %c\n", score, grade);
    return 0;
}

A score of 73 fails the first two tests and passes the third, so the grade is C. The order of the tests matters: each condition may assume that the conditions before it were false, which is why score >= 70 needs no upper bound.

$ gcc -std=c89 -pedantic -Wall -Wextra -o grades grades.c
$ ./grades
score 73, grade C

The dangling else

An else always belongs to the nearest preceding if that has no else, whatever the indentation says. The book shows the trap that follows from this rule, and GCC now warns about it.

dangling_else.c
#include <stdio.h>

int main()
{
    int n, a, b, z;

    n = 0;
    a = 5;
    b = 3;
    z = -1;

    if (n > 0)
        if (a > b)
            z = a;
    else
        z = b;

    printf("z = %d\n", z);
    return 0;
}

The indentation suggests that z becomes b when n is not positive. In fact, the else belongs to the inner if (a > b), so nothing is assigned when n is 0, and z keeps the value -1. Braces around the inner if give the intended meaning and silence the warning.

$ gcc -std=c89 -pedantic -Wall -Wextra -o dangling_else dangling_else.c
dangling_else.c: In function ‘main’:
dangling_else.c:12:8: warning: suggest explicit braces to avoid ambiguous ‘else’ [-Wdangling-else]
   12 |     if (n > 0)
      |        ^
$ ./dangling_else
z = -1

while and for

A while loop tests its condition before each pass and runs its body as long as the condition is nonzero. A for loop gathers the initialization, the test, and the step of such a loop in one line. The book opens with a temperature conversion table; this program prints a conversion table between miles and kilometres.

distances.c
#include <stdio.h>

#define LOWER 0
#define UPPER 100
#define STEP 20

int main()
{
    int miles, km;

    printf("miles\tkm\n");
    miles = LOWER;
    while (miles <= UPPER) {
        km = miles * 1609 / 1000;
        printf("%d\t%d\n", miles, km);
        miles = miles + STEP;
    }

    printf("\nkm\tmiles\n");
    for (km = LOWER; km <= UPPER; km += STEP)
        printf("%d\t%d\n", km, km * 1000 / 1609);
    return 0;
}

The table limits are symbolic constants, as in the book. The first table uses while with the three parts of the loop on separate lines; the second table uses for. The computation stays in integers: a mile is 1.609 km, so the program multiplies by 1609 and divides by 1000, and the fraction is dropped. The \t tabs align the columns.

$ gcc -std=c89 -pedantic -Wall -Wextra -o distances distances.c
$ ./distances
miles	km
0	0
20	32
40	64
60	96
80	128
100	160

km	miles
0	0
20	12
40	24
60	37
80	49
100	62

On the PDP-11 the first table goes wrong at 60 miles. 60 * 1609 is 96540, more than 16 bits can hold, and the multiplication overflows without a message. The second table goes wrong at 80 km for the same reason. A program for the PDP-11 computes such products in long, as in miles * 1609L / 1000.

$ cc distances.c
$ a.out
miles	km
0	0
20	32
40	64
60	31
80	63
100	29

km	miles
0	0
20	12
40	24
60	37
80	8
100	21

switch

A switch compares an integer expression with constant case labels and jumps to the matching one. Character constants are integers, so they are common case labels in K&R programs. Execution falls through from one case into the next unless a break ends it.

weekdays.c
#include <stdio.h>

int main()
{
    int day;

    for (day = 1; day <= 7; day++) {
        printf("day %d: ", day);
        switch (day) {
        case 1:
            printf("Monday, start of the week\n");
            break;
        case 5:
            printf("Friday, last working day\n");
            break;
        case 6:
        case 7:
            printf("weekend\n");
            break;
        default:
            printf("working day\n");
            break;
        }
    }
    return 0;
}

Days 6 and 7 share one branch: case 6 has no statements and falls through to case 7. Every other branch ends with break, which leaves the switch, not the for loop around it. The book recommends a break even after the last case, so that a case added later does not fall into it by accident. The default branch handles the values without a label.

$ gcc -std=c89 -pedantic -Wall -Wextra -o weekdays weekdays.c
$ ./weekdays
day 1: Monday, start of the week
day 2: working day
day 3: working day
day 4: working day
day 5: Friday, last working day
day 6: weekend
day 7: weekend

The comma operator

A pair of expressions separated by a comma is evaluated from left to right, and the value of the whole is the value of the right one. The comma operator is used mostly in for statements, to control two variables in one loop.

pairs.c
#include <stdio.h>

int main()
{
    int i, j, steps;

    steps = 0;
    for (i = 1, j = 10; i < j; i++, j--) {
        printf("%d + %d = %d\n", i, j, i + j);
        steps++;
    }
    printf("%d steps\n", steps);
    return 0;
}

i counts up from 1 and j counts down from 10 in the same loop, which stops when they meet. The commas in the argument list of printf are separators, not comma operators.

$ gcc -std=c89 -pedantic -Wall -Wextra -o pairs pairs.c
$ ./pairs
1 + 10 = 11
2 + 9 = 11
3 + 8 = 11
4 + 7 = 11
5 + 6 = 11
5 steps

do-while

A do-while loop tests its condition after the body, so the body runs at least once. The book uses it to convert a number to digits, because even the number 0 has one digit.

digits.c
#include <stdio.h>

int main()
{
    int n, sum, count;

    n = 1978;
    sum = 0;
    count = 0;

    printf("digits of %d from the right:", n);
    do {
        printf(" %d", n % 10);
        sum += n % 10;
        count++;
        n /= 10;
    } while (n > 0);
    printf("\n%d digits, sum %d\n", count, sum);

    n = 0;
    count = 0;
    do {
        count++;
        n /= 10;
    } while (n > 0);
    printf("0 has %d digit\n", count);
    return 0;
}

The loop takes the last digit with n % 10 and removes it with n /= 10, so the digits come out from right to left. For 0, a while loop would not run at all and would report no digits; the do loop counts the one digit correctly.

$ gcc -std=c89 -pedantic -Wall -Wextra -o digits digits.c
$ ./digits
digits of 1978 from the right: 8 7 9 1
4 digits, sum 25
0 has 1 digit

break and continue

break leaves the innermost loop or switch at once. continue skips the rest of the loop body and starts the next pass; in a for loop the step part runs first.

divisors.c
#include <stdio.h>

#define LIMIT 30

int main()
{
    int n, d, odd_sum;

    for (n = 2; n <= LIMIT; n++) {
        for (d = 2; d * d <= n; d++)
            if (n % d == 0)
                break;
        if (d * d > n)
            printf("%d ", n);
    }
    printf("are the primes up to %d\n", LIMIT);

    odd_sum = 0;
    for (n = 1; n <= LIMIT; n++) {
        if (n % 2 == 0)
            continue;
        odd_sum += n;
    }
    printf("the odd numbers up to %d add up to %d\n", LIMIT, odd_sum);
    return 0;
}

The inner loop looks for a divisor of n and stops with break at the first one. After the loop, the value of d tells why it ended: if d * d is greater than n, no divisor was found and n is a prime. The second loop skips the even numbers with continue.

$ gcc -std=c89 -pedantic -Wall -Wextra -o divisors divisors.c
$ ./divisors
2 3 5 7 11 13 17 19 23 29 are the primes up to 30
the odd numbers up to 30 add up to 225

goto and labels

goto jumps to a label in the same function. The book warns that it is easy to abuse and accepts it for one case: leaving several nested loops at once, which break cannot do.

squares.c
#include <stdio.h>

#define TARGET 65
#define MAX 10

int main()
{
    int i, j;

    for (i = 1; i <= MAX; i++)
        for (j = i; j <= MAX; j++)
            if (i * i + j * j == TARGET)
                goto found;

    printf("%d is not a sum of two squares up to %d\n", TARGET, MAX);
    return 0;

found:
    printf("%d = %d*%d + %d*%d\n", TARGET, i, i, j, j);
    return 0;
}

The nested loops search for two numbers whose squares add up to 65. When the pair is found, goto found leaves both loops, and i and j still hold the pair. A label is a name followed by a colon; it needs no declaration. If the loops end without a match, the first return ends the program before the label is reached.

$ gcc -std=c89 -pedantic -Wall -Wextra -o squares squares.c
$ ./squares
65 = 1*1 + 8*8

Declarations come first

In K&R C, the declarations of a block must come before its statements. A declaration after a statement or inside a for statement is not part of the language, and with -std=c89 -pedantic GCC reports both.

mixed_declarations.c
#include <stdio.h>

int main()
{
    int total;

    total = 0;
    int i;
    for (i = 1; i <= 3; i++)
        total += i;

    for (int k = 0; k < 2; k++)
        printf("%d\n", total);
    return 0;
}

The declaration of i after an assignment draws a warning, and the declaration of k in the for statement is an error. The K&R form declares i and k at the top of main, as all programs in this series do. The scope article shows that every block, not only the function body, may start with declarations.

$ gcc -std=c89 -pedantic -Wall -Wextra -o mixed_declarations mixed_declarations.c
mixed_declarations.c: In function ‘main’:
mixed_declarations.c:8:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
    8 |     int i;
      |     ^~~
mixed_declarations.c:12:5: error: ‘for’ loop initial declarations are only allowed in C99 or C11 mode
   12 |     for (int k = 0; k < 2; k++)
      |     ^~~
mixed_declarations.c:12:5: note: use option ‘-std=c99’, ‘-std=gnu99’, ‘-std=c11’ or ‘-std=gnu11’ to compile your code

Source

Dennis Ritchie: C Reference Manual (1975)

GCC: Options to Request or Suppress Warnings

In this article we have covered control flow in K&R C: integer conditions, else if chains and the dangling else, while and for loops, switch, the comma operator, do-while, break and continue, goto, and declarations at the start of a block. The next article, K&R C functions, splits programs into functions. The sorting and searching article returns to loops with the Shell sort from the book.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.