Codiqo

Learn C · lesson 23 of 60 · about 9 minutes

Scope and Prototypes

Add the report's last checks: see which variables a function can use, store the value it hands back, and declare it with a prototype so it can live below main.

What you'll learn

  • Explain local variables
  • See that arguments are copies
  • Write function prototypes

Last checks

Before the summary ends, the report runs two last checks: is space still low after the clean-up, and did the admin lock stay locked? Each problem should print why and add a warning. A function add_warning(warnings, reason) can do both, but it gets a copy of warnings, so it can't change main's variable. Instead it returns the new count, and main stores it: warnings = add_warning(warnings, "space still low");.

Each function has its own variables

Variables declared inside a function are local: they exist only while that function runs.

Arguments are copies. If a function changes its parameter, the caller's variable doesn't change. To change it, return the new value (or, later, use a pointer).

Changing a copy

#include <stdio.h>

void add_bonus(int score) {
    score += 10;
    printf("inside: %d\n", score);
}

int main(void) {
    int score = 5;
    add_bonus(score);
    printf("outside: %d\n", score);
    return 0;
}

Output

inside: 15
outside: 5

Prototypes

A prototype is a function's first line with a semicolon: int area(int w, int h);. Put prototypes at the top and you can define the functions after main, which keeps main near the top where readers look first.

main first, details later

#include <stdio.h>

int add(int a, int b);

int main(void) {
    printf("%d\n", add(2, 3));
    return 0;
}

int add(int a, int b) {
    return a + b;
}

Output

5

Warnings through a function below main

#include <stdio.h>

int add_warning(int warnings, const char *reason);

int main(void) {
    int warnings = 1;
    warnings = add_warning(warnings, "space still low");
    printf("Warnings: %d\n", warnings);
    return 0;
}

// prints the reason and hands back one more warning
int add_warning(int warnings, const char *reason) {
    printf("Warning: %s\n", reason);
    return warnings + 1;
}

Output

Warning: space still low
Warnings: 2

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.