What is const keyword in C: Explanation and Examples
const keyword is used to declare variables whose values cannot be changed after initialization. It tells the compiler to protect the variable from accidental modification, making the data read-only.How It Works
Think of the const keyword as a 'do not change' sign for a variable. When you declare a variable with const, you promise the program that this value will stay the same throughout the program. This helps prevent mistakes where a value might be changed by accident.
For example, if you have a number that should never change, like the number of days in a week, you can use const to make sure no part of your program changes it. The compiler will give an error if you try to modify a const variable, acting like a safety guard.
Example
This example shows how to declare a const variable and what happens if you try to change it.
#include <stdio.h> int main() { const int days_in_week = 7; printf("Days in a week: %d\n", days_in_week); // days_in_week = 8; // Uncommenting this line will cause a compile error return 0; }
When to Use
Use const when you want to protect values that should not change, like fixed settings, limits, or configuration values. It helps make your code safer and easier to understand because other programmers know these values are meant to stay constant.
For example, use const for mathematical constants like PI, or for fixed array sizes, or when passing data to functions that should not modify it.
Key Points
constmakes variables read-only after initialization.- Trying to change a
constvariable causes a compile-time error. - It improves code safety by preventing accidental changes.
- Commonly used for fixed values and function parameters that should not be modified.
Key Takeaways
const keyword in C creates variables that cannot be changed after they are set.const helps prevent bugs by protecting important values from accidental modification.const variable will cause a compile error, ensuring safety.const when you want to clearly communicate that a value should remain unchanged.