Read-only function parameters
What you'll learn: How to use the const keyword in function parameters to protect data from accidental modification.
The "Borrowing" Problem
When you pass a pointer to a function, you are handing that function the "keys" to your data. By default, the function can use that pointer to change the original variable’s value. This is powerful, but it’s also risky. Imagine lending a friend your favorite book so they can read it, but they return it with sentences crossed out and notes scribbled in the margins.
In C, we often want to pass a pointer for efficiency (to avoid copying large amounts of data) but ensure the function treats that data as "read-only."
Using const as a Safety Lock
By placing the const keyword before the data type in a function parameter, you are signing a contract. You are telling the compiler, "This function is allowed to look at this data, but it is not allowed to change it."
If the function tries to modify the data through that pointer, the compiler will throw an error and refuse to build the program. This turns a potential runtime bug into a simple compile-time fix.
Code Example: The Safe Print
In the example below, we pass a pointer to a large string. We use const to ensure the printing function doesn't accidentally mangle our text.
#include <stdio.h>
// The 'const' here means: "I can see the char, but I can't change it."
void displayMessage(const char* message) {
// We can read the data just fine
printf("Message of the day: %s\n", message);
// UNCOMMENTING THE LINE BELOW WOULD CAUSE A COMPILER ERROR:
// *message = 'B'; // Error: assignment of read-only location
}
int main() {
char myText[] = "Hello, World!";
displayMessage(myText);
return 0;
}
Why this matters
Using const parameters is a hallmark of professional C code. It makes your intentions clear to other programmers (and your future self). When you see const in a function signature, you know immediately that your data is safe. It allows you to pass large structures or arrays into functions without the overhead of copying, while maintaining the same security as passing by value.
Key takeaway
Use const in function parameters to grant read-only access to data, preventing accidental changes and making your code self-documenting.