Understanding C Constants: Unchangeable and Read-Only Variables
Learn about constants in C, which are unchangeable and read-only variables. Discover how to declare a constant using the const
keyword, ensuring that once set, the value cannot be modified, thus enhancing the stability and reliability of your code.
C Constants
What Are Constants?
In C, constants are variables that are unchangeable and read-only. To declare a constant, use the const
keyword. Once a variable is declared as constant, its value cannot be modified.
Declaring a Constant
Use the const
keyword to declare a variable as constant. For example, the following variable myNum
will always have the value of 15:
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
Output
error: assignment of read-only variable 'myNum'
You should declare variables as constants when the values are not meant to change. For example:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Notes on Constants
- When you declare a constant variable, it must be assigned a value immediately. You cannot assign a value later.
Correct Example
Correct Example
const int minutesPerHour = 60;
Incorrect Example
Incorrect Example
const int minutesPerHour;
minutesPerHour = 60; // error
Output
error: uninitialized 'const' variable
Good Practice
It is considered a good practice to declare constant variables in uppercase letters for better code readability. This is a common convention among C programmers:
Good Practice Example
const int BIRTHYEAR = 1980;