Scope and Function Prototypes

Local variables

A variable created inside a function only exists inside that function. This is its scope. Two functions can each have a variable called x, and they never get mixed up:

#include <stdio.h>

void other() {
    int x = 99;
    printf("x in other: %d\n", x);
}

int main() {
    int x = 5;
    other();
    printf("x in main: %d\n", x);
    return 0;
}

Output

x in other: 99
x in main: 5

Think of it like this: Local variables are like things in your own bedroom. Your sister may have a lamp in her room too, but turning off your lamp doesn't affect hers.

Parameters are copies

When you pass a variable to a function, the function gets a copy of the value. Changing the copy does not change the original:

#include <stdio.h>

void addTen(int n) {
    n = n + 10;
    printf("Inside: %d\n", n);
}

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

Output

Inside: 15
Outside: 5

Tip: To let a function change the original variable, you give it the variable's address with & – just like scanf. You'll learn how in Module 9 (Pointers).

Global variables

A variable made outside every function is global: every function can see it. Use them rarely – when everything can change a value, bugs are hard to find.

#include <stdio.h>

int visits = 0;   // global

void visit() {
    visits++;
}

int main() {
    visit();
    visit();
    visit();
    printf("Visits: %d\n", visits);
    return 0;
}

Output

Visits: 3

Prototypes: functions below main

Many programmers like main at the top. You can do that if you first write a prototype: just the first line of the function, ending with ;. It tells C "this function exists, its full code comes later":

#include <stdio.h>

int cube(int n);   // prototype

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

int cube(int n) {
    return n * n * n;
}

Output

27

Remember: Variables live inside their own { }. Parameters are copies. A prototype lets you call a function before its full code appears.

HOME LABS COMMUNITY DASHBOARD