Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

C Constant value Variables - const Keyword

If you want to create a variable whose value cannot be changed, then you can use the const keyword to create a constant value variable.

The variables which have type const, cannot be changed by the program. We can provide a value while defining the variable, and then, throughout the program, that variable will hold the same value.

Using const Keyword

Here is a simple example for using the const keyword,

const int totalmarks = 100;

In the above code, we have defined a variable with name totalmarks and assigned it a value 100. Because we have used the const keyword while defining the variable hence we cannot change the value of the totalmarks variable.

Change const Variable value

If you will try to change the value of the const variable in the program after it has been defined, then the compiler will give an error.

For example,

#include <stdio.h>

int main() {
   // initialize a constant variable 
   const int total_marks = 10;

   // try changing value
   total_marks = 80;
   return 0;

error: assignment of read-only variable 'total_marks'
total_marks = 80;

Run Code →

As you can see in the error message, the compiler says that the variable is a read-only variable, hence its value cannot be changed.

Because const variables are read-only variables, the compiler can place these variables into the read-only memory (ROM).

When we define a variable as const, then nothing in that program can change the value of that variable.

Hence, if the value of the const variable changes, then you can say that something outside of the program changed the value, it can be the hardware device or any external event.


In this tutorial, we learned how to create constant value variables, which are the variable whose values cannot be changed by the program.