Course contentsShow
← C
Lesson 333 of 1,2195. FunctionsFree lesson

Scope of function declarations

Scope of function declarations

What you'll learn: How the placement of a function prototype determines which parts of your code are allowed to call that function.

The "VIP List" Analogy

Imagine you are throwing a party in a large house with several rooms. A function declaration (or prototype) is like a VIP list. If you nail the list to the front door of the house, every guest in every room knows who is invited. However, if you only tuck that list into the corner of the Kitchen, the people in the Living Room have no idea who is on it.

In C, the "house" is your file, and the "rooms" are your individual functions. Where you place your declaration determines its scope—the area of code where the function is "visible" and ready to be used.

Global Scope: The Front Door

Most of the time, you will place prototypes at the very top of your file, outside of any curly braces. This gives them file scope. Any function written below that line can see and call that function. This is the standard way to organize code because it prevents "identifier not found" errors regardless of how you order your logic.

Local Scope: The Private Room

You can also declare a function inside the body of another function. This gives it block scope. When you do this, you are telling C: "Only this specific function is allowed to know that this other function exists."

#include <stdio.h>

// Global scope: Anyone below this can call 'calculate_tax'
float calculate_tax(float income);

void accounting_dept() {
    // Local scope: Only the accounting_dept knows 'secret_bonus' exists
    int secret_bonus(int performance_score);
    
    printf("Tax: %f", calculate_tax(50000)); // Works!
    printf("Bonus: %d", secret_bonus(10));   // Works!
}

void cafeteria_staff() {
    printf("Tax: %f", calculate_tax(30000)); // Works!
    // printf("%d", secret_bonus(5));        // ERROR! The cafeteria doesn't know about the secret_bonus.
}

Why limit scope?

While global scope is convenient, local scope is used when you want to enforce strict boundaries. It prevents a function from being used accidentally in parts of the program where it doesn't belong. However, in modern C development, local function declarations are rare. Usually, if a function is meant to be private, we use other tools (like the static keyword), but understanding scope helps you debug why the compiler might insist a function doesn't exist even though you clearly wrote it elsewhere!

Key takeaway

Function prototypes placed outside all blocks have file scope (global), while prototypes inside a function have block scope (local) and are invisible to the rest of the program.