Course contentsShow
← C
Lesson 1198 of 1,21916. Practice and ProjectsFree lesson

The role of `const` in documentation

The role of const in documentation

What you'll learn: How to use the const keyword as a "contract" that tells other programmers exactly how your functions treat their data.

The "Read-Only" Promise

When you are working on a professional team, your code is read far more often than it is written. Other developers will look at your function signatures to understand how to interact with your code. Using const isn't just about telling the compiler to throw an error if a value changes; it’s a form of professional communication.

Think of a function parameter like a borrowed tool. If a neighbor borrows your lawnmower, you’d be much more comfortable if they signed a contract promising to return it exactly as they found it. In C, const is that contract. It tells the caller, "You can give me a pointer to your precious data, and I promise I will only look at it—I won't change a single bit."

Code as a Manual

Without const, a developer looking at your header file has to guess. If they see void process_data(char *str), they have to wonder: Does this function modify my string? Do I need to make a backup copy before calling this?

When you add const, you remove the guesswork. You are documenting the "flow" of data.

// Documentation via code: 
// 'source' is an input (read-only).
// 'dest' is an output (modified).
void smart_copy(char *dest, const char *source) {
    // The compiler enforces the promise:
    // source[0] = 'A'; // This would cause a compile error.
    
    while ((*dest++ = *source++));
}

Building Trust in Large Projects

In professional projects with thousands of lines of code, you cannot keep the logic of every function in your head. const creates a "safe zone." When you see a variable passed as const, your brain can stop worrying about that variable's state changing unexpectedly.

It also signals intent. If you write a function to calculate_total(const int *prices), you are telling the world that this function is a "pure" observer. This makes your code more predictable, easier to debug, and much more welcoming to other developers who have to use your work.

Key takeaway

Use const for input parameters to document that a function is safe, read-only, and won't produce side effects on the passed data.