The const qualifier on variables
What you'll learn: You will understand how to use the const keyword to create read-only variables that protect your data from accidental modification.
The "Read-Only" Guard
In C, the const qualifier is a promise you make to the compiler. When you mark a variable as const, you are telling the computer: "I will set this value once, and I want you to prevent me from ever changing it again."
Think of a standard variable like a whiteboard. You can write a number on it, rub it out, and write a new one whenever you like. A const variable is more like a stone tablet. You carve the value into it at the very beginning, and if you try to take an eraser to it later, the compiler will step in and stop you before the program even runs.
Why Use It?
You might wonder why you would want to limit yourself. Programming is often about managing complexity and preventing human error. If you are calculating the area of circles, you know that Pi should always be 3.14159. By declaring it as const, you ensure that no buggy line of code later in your program can accidentally change Pi to 4.0 or 0.0, which would break every calculation following it.
Seeing it in Action
To create a constant, place the const keyword before or after the data type. You must initialize it (give it a value) the moment you declare it.
#include <stdio.h>
int main() {
// A standard variable can change
int score = 100;
score = 150;
// A constant variable is locked
const double PI = 3.14159;
// The line below would cause a "read-only variable" compiler error:
// PI = 3.14;
printf("The value of PI is: %f\n", PI);
return 0;
}
Important Nuance
It is important to remember that const does not mean the value is "constant" in the sense of a mathematical literal (like the number 5). It simply means the variable is read-only. It still occupies memory, but the compiler enforces a strict "no-write" policy on that specific memory location. This helps the compiler optimize your code and makes your intentions clear to anyone else reading your work.
Key takeaway
The const qualifier creates a read-only variable that must be initialized at declaration and cannot be modified thereafter.