CC

C: Control flow – code examples

Contents

if / else if / else

Control flow#if#conditionCompare in all languages
Use case: React differently depending on the case, e.g. to evaluate grades, price tiers or status codes.
#include <stdio.h>

int main(void) {
    int punkte = 73;
    if (punkte >= 90) {
        printf("very good\n");
    } else if (punkte >= 70) {
        printf("good\n");
    } else {
        printf("needs improvement\n");
    }
    return 0;
}

Conditions go in parentheses, blocks in curly braces. Every value other than 0 counts as true.

for loop

Control flow#for#loop#arrayCompare in all languages
Use case: Repeat n times or process every element of an array.
#include <stdio.h>

int main(void) {
    for (int i = 0; i < 3; i++) {
        printf("Round %d\n", i);
    }
    const char *fruechte[] = {"Apple", "Pear"};
    for (size_t i = 0; i < 2; i++) {
        printf("%s\n", fruechte[i]);
    }
    return 0;
}

The first loop counts 0, 1, 2; the second iterates by index over an array of strings (C has no for-each).

enum with switch

Control flow#enum#switch#state
Use case: Name states cleanly, e.g. traffic light phases, protocol states or error codes.
#include <stdio.h>

enum Ampel { ROT, GELB, GRUEN };

const char *aktion(enum Ampel a) {
    switch (a) {
        case ROT:   return "stop";
        case GELB:  return "get ready";
        case GRUEN: return "go";
    }
    return "unknown";
}

int main(void) {
    for (int a = ROT; a <= GRUEN; a++) printf("%d: %s\n", a, aktion(a));
    return 0;
}

Compilers with -Wall warn when a case is missing in a switch over an enum. This protects you when extending the code later.