Const Qualifier in C Language with Examples

const qualifier in c

In this tutorial, you will learn the const qualifier and its usage in C programming with example code.

Generally, when we start learning the C programming language, the following questions comes to our mind.

  • What does const mean in C?
  • How to use the const Qualifier to define constants in C?
  • Why do we use const in C?
  • Where are constant variables stored in C?
  • When should you use the const keyword?
  • How do I best use the const keyword in C?
  • What is the const qualifier in C explain with examples?
  • What is the difference between macro and constant?

These questions also came to my mind when I have started learning. So if you are searching for the answer to any of the mentioned questions, then you are at the right place. We will clear your all doubts, but still if you have any doubt you ask your question related to the const keyword in the comment box.

 

👍 Click to Directly Jump to Video Lecture (Hindi):

 

What is a const qualifier in C?

According to C11, C supports 4 types of type qualifiers these are const (C89), volatile (C89), restrict (C99), and _Atomic (C11). So const is one of the four type qualifiers.

The const type qualifier declares an object to be nonmodifiable. The const keyword specifies that a variable’s value is constant and tells the compiler to prevent the programmer from modifying it.

Syntax of const object in C:

To make a variable constant, you only need to add the const qualifier at the time of variable declaration, see the below-mentioned statement:

const <data_type> <var_name> = <value>;

e.g,

const int iData = 2; //data is constant

 

Now I believe you are able to understand “how to use the const qualifier to define constants in C”. In the above example, iData is constant, we can not modify its value. In simple words, iData is not modifiable.

//iData without const
int iData = 2; //iData is variable-> modifiable

iData = 3; // Ok



//iData with const
const int iData = 2; //iData is constant -> non-modifiable

iData = 3; // Error

See the below image for a better understanding.

const qualifier in C

 

Why do we use const in C?

As of now, we have learned, the const keyword specifies that the object or variable is not modifiable. It means the program could not change the value of the const qualify object or variable.

So whenever we want to make any variable non-modifiable we qualify it with a const type qualifier. The const is most useful with parameter passing, you can find it in many standard library functions like strtok, memcpy, strncpy, .etc.

 

Consider the below example code,

The following example code explains that if you try to modify the const qualify object, you will get the compiler error.

In the below code, we have used the const keyword with the variable “i” because we don’t want our program to change its value. When the program tries to modify its value, we will get the compiler error.

#include <stdio.h>
int main()
{
    //const qualify object
    const int i = 5;

    i = 10;   //error

    i++;    //error

    return 0;
}

Output:

Why do we use const in C_Aticleworld

 

 

How to modify the value of the const variable?

If you are thinking to modify the const variable value, then it is the biggest mistake of your life.

Ha, Ha, Ha, why I am saying this is because when you will search this question that “Can we change the value of an object defined with const through pointers?” or ” how to modify the const variable value” or “how to modify const int with pointer”, you will get the solution.  But believe me, these are hack and put you in problem.

If I am talking about the C standard it simply says that “If an attempt is made to modify an object defined with a const-qualified type through the use of an lvalue with a non-const-qualified type, the behavior is undefined“.

It means if you try to modify the value of the const variable, the behavior of your program would be undefined. You can’t predict what will happen when you try this. Consider the below example,

#include <stdio.h>

int main()
{
    //const-qualified integer
    const int data = 5;

    //non-const-qualified type
    int * ptr = NULL;

    //breaking the promise
    ptr = (int*)&data;

    *ptr = 6;

    printf("*ptr = %d",*ptr);

    return 0;
}

Output: Behavior is undefined (UB).

 

Personally, I have faced this issue and we have spent many hours to find this issue. Our code base was working in debug mode but was not working in release mode and such type of issue is hard to find. If you properly suppress the warning with typecasting.

 

Where are constant variables stored in C?

When we declare a variable as constant, it depends on the implementation (depends on the compiler), how they are stored. On most machines, read-only variables, constants, and jump tables are placed in the text section (it’s read-only and contains all executable instructions).

According to the C standard “the implementation can place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used”.

Note: When optimization is enabled, a compiler will generally try to make constants as efficient as possible. For example, if you write x = 30*2 + 5, the compiler would reduce this to 65 at compile time rather than putting 30, 2, and 5 in the compiled program.

 

If you are not familiar with the memory layout of the C programming, you can check this article “Memory layout of C program“.

 

When should you use the const keyword?

Personally, I follow one golden rule use const as much as possible. But here addressing a few places where you should use the const keyword.

1. You must use the const with function parameters passed by reference where the function does not modify (or free) the data pointed to.

int displayMessage ( const char *pcMessage);

2.When you don’t want to change the value of the variable after the initialization.

int i = 2;

If the value of “i” will not change throughout his life, then we must use const with it.

const int i = 2;

 

3.Use type-safe constant in place of the macro because constants are handled by the compiler. Also constant is following the scoped rule with the added benefit of type safety.

static const int data = 90;

4. When mapping I/O registers, use const and volatile together as much as possible.

const volatile uint32_t *DEVICE_STATUS = (const volatile uint32_t*) 0x2706;

 

 

Use of const with pointers:

Like the simple variable, we can also use the const with pointers. The const keyword is useful for declaring pointers to const since this requires the function not to change the pointer in any way. Let’s see some legal const and pointer declarations:

The following are legal const declarations with a pointer:

  1. int const *ptr; // Pointer to constant int
  2. const int *ptr; // Pointer to constant int
  3. int *const ptr; // Constant pointer to int
  4. int (*const ptr); // Constant pointer to int
  5. const int *const ptr; // Constant pointer to const int
  6. int const *const ptr; // Constant pointer to const int

 

Let’s see some of the popular usages of const and pointer together with the help of programming examples.

Pointer to const int (pointer to constant integer):

const int *piData;
        or
int const *piData;

This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn’t be changed. Const qualifier doesn’t affect the pointer in this scenario so the pointer is allowed to point to some other address.

The above declaration described that piData is pointing to a constant integer. It means that the pointer is referring to a value that should not be modified.

So we can not change the value of the pointed integer variable using the pointer (*piData). But const qualifier doesn’t affect the pointer(piData) in this scenario so the pointer is allowed to point to some other address.

Consider the below code, where I am trying to modify the value of the integer using the pointer to const integer. I will get here compiler error because I am breaking the promise.

#include <stdio.h>

int main()
{
    //Integer variable
    int data = 2;

    //pointer to const int
    const int *piData = NULL;


    /*
    Assign the address of iIndexData
    to a pointer to const,here integer
    variable qualify to const integer
    its called up qualification which is valid in c
    */
    piData = &data;

    //Try to change data constant object
    *piData = 3;

    printf("Data is %d",*piData);

    return 0;
}

OutPut:

error: assignment of read-only location ‘*piData’

 

Now I am modifying my code and changing the value of the pointer, which means now pointer pointing to a different address. You can see the below code it will work perfectly.

#include <stdio.h>

int main()
{
    //Integer variable1
    int data1 = 2;

    //Integer variable2
    int data2 = 4;

    /*
    Assign address of integer variable to pointer to const,
    here integer variable qualify to const integer
    */
    const int* piData = &data1;

    //Display data
    printf("*piData is %d\n",*piData);

    //It's valid because pointer is not a constant
    piData = &data2;

    printf("*piData is %d\n",*piData);

    return 0;
}

OutPut:

*piData is 2
*piData is 4

 

Constant pointer to int (Constant pointer to integer variable):

int *const piData;

The above declaration described that a constant pointer is pointing to an integer variable. It means the pointer is itself not modifiable (piData cannot point to the other object) but we can change the value of the integer variable pointed by the pointer. Const qualifier doesn’t affect the pointed integer.

Consider the below code, where I am trying to modify the piData (pointer). I will get here compiler error because I am breaking the promise.

#include <stdio.h>

int main(void)
{
    /*Integer variable1*/
    int Data1 = 2;
    /*Integer variable2*/
    int Data2 = 4;

    int* const piData = &Data1;
    //Display data
    printf("*piData is %d\n",*piData);

    /*It's invalid because pointer is constant*/
    piData = &Data2;
    printf("*piData is %d\n",*piData);

    return 0;
}

OutPut:

Error: assignment of read-only variable ‘piData’

 

constant pointer to a constant int (constant pointer to a constant int):

const int *const piData;

The above declaration described that a constant pointer is pointing to a constant integer variable. Here const keywords affect both pointer and pointed integer variables. Hence, neither the pointer should point to a new address nor the value being pointed to should be changed.

Everything will be good if you don’t try to change the value of piData and *piData.

#include <stdio.h>

int main(void)
{
    //Integer variable1
    int Data = 2;

    //const pointer to const int
    const int *const piData = &Data;

    printf("*piData is %d\n",*piData);

    return 0;
}

OutPut:

*piData is 2

 

If you will try to change the value of *piData then you will get the compiler error because here *piData qualifies to constant.

#include <stdio.h>

int main(void)
{
    //Integer variable
    int Data = 2;

    //const pointer to const int
    const int *const piData = &Data;

    //change the value
    *piData = 3;

    printf("*piData is %d\n",*piData);

    return 0;
}

Output:

Error: assignment of read-only location ‘*piData’

 

If you try to point another integer variable to the pointer, you will get the compiler error.

#include <stdio.h>
int main(void)
{
    /*Integer variable1*/
    int Data1 = 2;
    /*Integer variable2*/
    int Data2 = 4;
    const int* const piData = &Data1;
    //Display data
    printf("*piData is %d\n",*piData);
    /*It's invalid because pointer is constant*/
    piData = &Data2;
    printf("*piData is %d\n",*piData);
    return 0;
}

OutPut:

Error: assignment of read-only variable ‘piData’

 

Video tutorial on Const keyword in Hindi:

Check some important questions related to the const keyword, Click Here:

Recommended Post

6 comments

  1. Hii…
    In the first case i:e; pointer to a constant object, you have said if you change the value of *piIndex directly as *piIndex = 3; you will get an error. That’s fine. But if you change the value of iIndexData1 to 3 and if you print
    printf(“Value of object is %d\n”,*piIndex);
    Then you will get 3. How is it possible? am I understood it correct?

    1. Check the below code but it is not a good way output can be undefined.

      #include

      int main(void) {

      int iIndexData1 = 2; /*Integer variable1*/
      const int *piIndex = NULL; /*pointer to const int*/

      piIndex = &iIndexData1; /*Assign the address of iIndexData
      to a pointer to const,here integer
      variable qualify to const integer
      its called up qualification which is valid in c*/

      iIndexData1 = 3;
      printf(“Data is %d”,*piIndex);

      return 0;
      }

Leave a Reply

Your email address will not be published. Required fields are marked *