C const Qualifier Tutorial

In this section we will learn what the const qualifier is and how to use it in C.

What is const Qualifier in C?

Sometimes we want to have a variable in a program that can only be used for reading and not writing!

For example, the value of PI in Math is 3.14… and we know that this value is always constant and won’t change under different circumstances.

So if we create a variable `double pi = 3.14` we know that the value assigned to this variable does not need to change at all.

In such cases we can turn the target variable into read-only variable via the `const` qualifier. As a result, we’re only allowed to assign a value to a read-only variable just at the time of declaration.

Any other attempt to assign a value to a read-only variable after its declaration will result in an error.

Declaring const Variable in C

Here’s how we can use `const` qualifier in order to turn a variable into read-only or constant variable.

Data-type const variable-name = assigned-value;
const data-type variable-name = assigned-value;

Note: you need to assign a value to a read-only variable right when is declared. Any attempt to reassign or update the value of a read-only variable will result to error.

Example: creating const variable in C

#include <stdio.h>

int main() {

    int const first = 200;
    const int second = 400;


    return 0;
}

Example: assigning to a const variable

#include <stdio.h>

int main() {

    int const first = 200;
    const int second = 400;

    first = 500;
    second = 1000;

    return 0;
}

Output:

error: assignment of read-only variable 'first'

first = 500;

There’s another way to create a constant variable (read-only) as well, and that is via the use #define preprocessor directive. We will talk about it in the #define section.

Difference between Constant and Variable

The main difference is that a const identifier can’t take another value after its initialization. Basically, we can’t reassign such type of identifier.

On the other hand, a variable is capable of reassigning at any time during the life of a program.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies