Course contentsShow
← C
Lesson 912 of 1,21913. Advanced CFree lesson

Using `const` in function parameters

Using const in function parameters

What you'll learn: How to use the const qualifier to create read-only contracts for your function arguments, preventing accidental data modification.

The "Read-Only" Contract

When you pass a variable to a function by value (like a simple int), the function gets a copy. If the function changes that copy, the original stays safe. However, in C, we often pass pointers to avoid copying large amounts of data. The danger here is that a function could accidentally change the data at that memory address, affecting your original variable.

Think of it like giving someone the keys to your house. By default, they could paint the walls or move the furniture. By using const, you are giving them the keys but adding a legal contract that says: "You can look around, but you aren't allowed to change a single thing."

Protect Your Data

When you declare a pointer parameter as const, you are telling the compiler to throw an error if the function attempts to modify the value being pointed to. This is essential for functions that only need to "read" or "inspect" data, such as a function that prints a string or calculates the average of an array.

#include <stdio.h>

// The 'const' here tells the compiler: "we will not change the text"
void displayMessage(const char *message) {
    // This is allowed: reading the data
    printf("Message of the day: %s\n", message);

    // This would cause a compiler error:
    // message[0] = 'H'; 
}

int main() {
    char myText[] = "Hello World";
    displayMessage(myText);
    return 0;
}

Why Bother?

You might think, "I'll just be careful not to change the data." However, const provides two massive benefits:

  1. Security against bugs: In large projects, you might forget your own intentions. The compiler acts as a safety net, stopping you the moment you try to write to "read-only" memory.
  2. Self-documenting code: When another programmer (or your future self) reads your function signature, the const keyword immediately tells them: "This function is safe to use; it won't mess with my original data."

By using const whenever possible, you create "code that explains itself," making your programs more robust and easier to debug.

Key takeaway

Use const in function parameters to protect original data from accidental modification and to clearly signal a function's intent to other developers.