The const qualifier
What you'll learn: How to protect variables from being changed after they are created using the const keyword.
The "Read-Only" Shield
In programming, a variable is usually like a dry-erase board: you write a value down, and later, you can wipe it away to write something new. However, sometimes you want a value to be written in permanent ink.
Maybe you are defining the value of Pi (3.1415), or perhaps you are setting a maximum player limit for a game. You don't want a bug in your code to accidentally change these values halfway through the program. In C, we use the const qualifier to tell the compiler, "This value is read-only. Do not let anything change it."
Using const in Code
To make a variable a constant, you simply add the word const before the data type. Once you do this, you must give the variable its value immediately (initialization). If you try to change it later, the compiler will throw an error and refuse to build your program.
#include <stdio.h>
int main() {
// A normal variable can change
int score = 0;
score = 10;
// A constant variable is locked
const int MAX_USERS = 50;
const float PI = 3.14159;
// The following line would cause a compiler error:
// MAX_USERS = 100;
printf("The limit is %d users.\n", MAX_USERS);
return 0;
}
Why bother?
You might wonder, "If I'm the one writing the code, can't I just promise not to change the variable?"
Think of const as a safety rail. On large projects with thousands of lines of code and multiple programmers, it is very easy to accidentally reuse a variable name or overwrite a value. By using const, you are offloading the work of "remembering" to the computer. If you accidentally try to change a constant, the computer catches the mistake for you instantly. It also tells anyone reading your code, "This value is a fixed rule for this program."
Key takeaway
The const keyword creates a read-only variable that acts as a safeguard against accidental changes.