Constant arrays with the const qualifier
What you'll learn: How to protect your array data from accidental changes by using the const keyword.
The "Read-Only" Guard
Imagine you are writing a program for a vending machine. You have an array that stores the prices of various snacks. These prices shouldn't change while the program is running; a bag of chips that costs 0.00 because of a coding typo or a logic error elsewhere in your software.
In C, we use the const qualifier to tell the compiler that an array is "read-only." Once you initialize a constant array, its values are locked in. If you—or another programmer—accidentally try to write code that changes an element, the compiler will throw an error and refuse to build the program. This turns a potentially disastrous runtime bug into a simple compile-time fix.
Using const in Code
To create a constant array, simply place the word const before the data type during declaration. You must initialize the array immediately, as you won't be allowed to assign values to it later.
#include <stdio.h>
int main() {
// A constant array of prime numbers
const int primes[] = {2, 3, 5, 7, 11};
// We can read from it perfectly fine
printf("The third prime is %d\n", primes[2]);
// The following line would cause a compiler error:
// primes[0] = 4; // Error: assignment of read-only location
return 0;
}
Why Bother?
You might wonder: "If I'm the one writing the code, can't I just promise not to change the array?" In small projects, perhaps. But as programs grow, "defensive programming" becomes essential.
Using const provides two main benefits. First, it acts as documentation; anyone reading your code instantly knows that this data is a fixed reference. Second, it allows the compiler to optimize your code better, as it knows those memory values will never shift. It is a simple tool that provides a safety net for your most important data.
Key takeaway
Use the const qualifier for arrays that represent fixed data to prevent accidental modifications and catch errors during compilation.