Open In App

Const Qualifier in C

Last Updated : 07 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to change a const.

Using the const qualifier in C is a good practice when we want to ensure that some values should remain constant and should not be accidentally modified.

In C programming, the const qualifier can be used in different contexts to provide various behaviors. Here are some different use cases of the const qualifier in C:

1. Constant Variables

const int var = 100;

In this case, const is used to declare a variable var as a constant with an initial value of 100. The value of this variable cannot be modified once it is initialized. See the following example:

C




// C program to demonstrate that constant variables can not
// be modified
#include <stdio.h>
 
int main()
{
    const int var = 100;
 
    // Compilation error: assignment of read-only variable
    // 'var'
    var = 200;
 
    return 0;
}


Output

./Solution.cpp: In function 'int main()':
./Solution.cpp:11:9: error: assignment of read-only variable 'var'
     var = 200;
         ^

2. Pointer to Constant

const int* ptr;

OR

int const *ptr;

We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case). The object pointed may be in the read-only or read-write area. Let us see the following examples.

Example 1:

C




// C program to demonstrate that  the pointer to point to
// any other integer variable, but the value of the object
// (entity) pointed can not be changed
 
#include <stdio.h>
int main(void)
{
    int i = 10;
    int j = 20;
    /* ptr is pointer to constant */
    const int* ptr = &i;
 
    printf("ptr: %d\n", *ptr);
    /* error: object pointed cannot be modified
    using the pointer ptr */
    *ptr = 100;
 
    ptr = &j; /* valid */
    printf("ptr: %d\n", *ptr);
 
    return 0;
}


Output

./Solution.c: In function 'main':
./Solution.c:12:10: error: assignment of read-only location '*ptr'
     *ptr = 100;
          ^

Example 2: Program where variable i itself is constant.

C




// C program to demonstrate that  the pointer to point to
// any other integer variable, but the value of the object
// (entity) pointed can not be changed
 
#include <stdio.h>
 
int main(void)
{
    /* i is stored in read only area*/
    int const i = 10;
    int j = 20;
 
    /* pointer to integer constant. Here i
    is of type "const int", and &i is of
    type "const int *".  And p is of type
    "const int", types are matching no issue */
    int const* ptr = &i;
 
    printf("ptr: %d\n", *ptr);
 
    /* error */
    *ptr = 100;
 
    /* valid. We call it up qualification. In
    C/C++, the type of "int *" is allowed to up
    qualify to the type "const int *". The type of
    &j is "int *" and is implicitly up qualified by
    the compiler to "const int *" */
 
    ptr = &j;
    printf("ptr: %d\n", *ptr);
 
    return 0;
}


Output

./Solution.c: In function 'main':
./Solution.c:18:10: error: assignment of read-only location '*ptr'
     *ptr = 100;
          ^

Down qualification is not allowed in C++ and may cause warnings in C. Down qualification refers to the situation where a qualified type is assigned to a non-qualified type.

Example 3: Program to show down qualification.

C




// C program to demonstrate the down qualification
 
#include <stdio.h>
 
int main(void)
{
    int i = 10;
    int const j = 20;
 
    /* ptr is pointing an integer object */
    int* ptr = &i;
 
    printf("*ptr: %d\n", *ptr);
 
    /* The below assignment is invalid in C++, results in
       error In C, the compiler *may* throw a warning, but
       casting is implicitly allowed */
    ptr = &j;
 
    /* In C++, it is called 'down qualification'. The type
       of expression &j is "const int *" and the type of ptr
       is "int *". The assignment "ptr = &j" causes to
       implicitly remove const-ness from the expression &j.
       C++ being more type restrictive, will not allow
       implicit down qualification. However, C++ allows
       implicit up qualification. The reason being, const
       qualified identifiers are bound to be placed in
       read-only memory (but not always). If C++ allows
       above kind of assignment (ptr = &j), we can use 'ptr'
       to modify value of j which is in read-only memory.
       The consequences are implementation dependent, the
       program may fail
       at runtime. So strict type checking helps clean code.
     */
 
    printf("*ptr: %d\n", *ptr);
 
    return 0;
}


Output

main.c: In function ‘main’:
main.c:16:9: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
   16 |     ptr = &j;
      |         ^
*ptr: 10
*ptr: 20

3. Constant Pointer to Variable

int* const ptr;

The above declaration is a constant pointer to an integer variable, which means we can change the value of the object pointed by the pointer, but cannot change the pointer to point to another variable.

Example

C




// C program to demonstrate that the value of object pointed
// by pointer can be changed but the pointer can not point
// to another variable
 
#include <stdio.h>
 
int main(void)
{
    int i = 10;
    int j = 20;
    /* constant pointer to integer */
    int* const ptr = &i;
 
    printf("ptr: %d\n", *ptr);
 
    *ptr = 100; /* valid */
    printf("ptr: %d\n", *ptr);
 
    ptr = &j; /* error */
    return 0;
}


Output

./Solution.c: In function 'main':
./Solution.c:15:9: error: assignment of read-only variable 'ptr'
     ptr = &j; /* error */
         ^

4. Constant Pointer to Constant

const int* const ptr;

The above declaration is a constant pointer to a constant variable which means we cannot change the value pointed by the pointer as well as we cannot point the pointer to other variables. Let us see with an example. 

C




// C program to demonstrate that value pointed by the
// pointer can not be changed as well as we cannot point the
// pointer to other variables
 
#include <stdio.h>
 
int main(void)
{
    int i = 10;
    int j = 20;
    /* constant pointer to constant integer */
    const int* const ptr = &i;
 
    printf("ptr: %d\n", *ptr);
 
    ptr = &j; /* error */
    *ptr = 100; /* error */
 
    return 0;
}


Output

./Solution.c: In function 'main':
./Solution.c:12:9: error: assignment of read-only variable 'ptr'
     ptr = &j; /* error */
         ^
./Solution.c:13:10: error: assignment of read-only location '*ptr'
     *ptr = 100; /* error */
          ^

Advantages of const Qualifiers in C

The const qualifier in C has the following advantages:

  • Improved Code Readability: By marking a variable as const, you indicate to other programmers that its value should not be changed, making your code easier to understand and maintain.
  • Enhanced Type Safety: By using const, you can ensure that values are not accidentally modified, reducing the chance of bugs and errors in your code.
  • Improved Optimization: Compilers can optimize const variables more effectively, as they know that their values will not change during program execution. This can result in faster and more efficient code.
  • Better Memory Usage: By declaring variables as const, you can often avoid having to make a copy of their values, which can reduce memory usage and improve performance.
  • Improved Compatibility: By declaring variables as const, you can make your code more compatible with other libraries and APIs that use const variables.
  • Improved Reliability: By using const, you can make your code more reliable, as you can ensure that values are not modified unexpectedly, reducing the risk of bugs and errors in your code.

Summary

Type Declaration Pointer Value Change
(*ptr = 100)
Pointing Value Change
(ptr  = &a)
Pointer to Variable int * ptr Yes Yes
Pointer to Constant const int * ptr
int const * ptr
No Yes
Constant Pointer to Variable int * const ptr Yes No
Constant Pointer to Constant const int * const ptr No No

This article is compiled by “Narendra Kangralkar“.



Previous Article
Next Article

Similar Reads

Difference between const char *p, char * const p and const char * const p
Prerequisite: Pointers There is a lot of confusion when char, const, *, p are all used in different permutations and meanings change according to which is placed where. Following article focus on differentiation and usage of all of these. The qualifier const can be applied to the declaration of any variable to specify that its value will not be cha
3 min read
How does Volatile qualifier of C works in Computing System
Prerequisite: Computing systems, Processing unit Processing Unit:Processing units also have some small memory called registers.The interface between the processor (processing unit) and memory should work on the same speed for better performance of the system.Memory: In memory, there are two types, SRAM and DRAM. SRAM is costly but fast and DRAM is
3 min read
Understanding "volatile" qualifier in C | Set 1 (Introduction)
In spite of tons of literature on C language, "volatile" keyword is somehow not understood well (even by experienced C programmers). We think that the main reason for this is due to not having real-world use-case of a 'volatile' variable in typical C programs that are written in high level language. Basically, unless you're doing some low level har
5 min read
Understanding "volatile" qualifier in C | Set 2 (Examples)
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the curre
5 min read
C++ | const keyword | Question 1
Predict the output of following program #include &lt;iostream&gt; using namespace std; int main() { const char* p = &quot;12345&quot;; const char **q = &amp;p; *q = &quot;abcde&quot;; const char *s = ++p; p = &quot;XYZWVU&quot;; cout &lt;&lt; *++s; return 0; } (A) Compiler Error (B) c (C) b (D) Garbage Value Answer: (B) Explanation: Output is ‘c’ c
1 min read
C++ | const keyword | Question 2
In C++, const qualifier can be applied to 1) Member functions of a class 2) Function arguments 3) To a class data member which is declared as static 4) Reference variables (A) Only 1, 2 and 3 (B) Only 1, 2 and 4 (C) All (D) Only 1, 3 and 4 Answer: (C) Explanation: When a function is declared as const, it cannot modify data members of its class. Whe
1 min read
C++ | const keyword | Question 3
Predict the output of following program. #include &lt;iostream&gt; using namespace std; class Point { int x, y; public: Point(int i = 0, int j =0) { x = i; y = j; } int getX() const { return x; } int getY() {return y;} }; int main() { const Point t; cout &lt;&lt; t.getX() &lt;&lt; &quot; &quot;; cout &lt;&lt; t.getY(); return 0; } (A) Garbage Value
1 min read
C++ | const keyword | Question 5
#include &lt;stdio.h&gt; int main() { const int x; x = 10; printf(&quot;%d&quot;, x); return 0; } (A) Compiler Error (B) 10 (C) 0 (D) Runtime Error Answer: (A) Explanation: One cannot change the value of 'const' variable except at the time of initialization. Compiler does check this.Quiz of this Question
1 min read
C++ | const keyword | Question 5
Output of C++ program? #include &lt;iostream&gt; int const s=9; int main() { std::cout &lt;&lt; s; return 0; } Contributed by Pravasi Meet (A) 9 (B) Compiler Error Answer: (A) Explanation: The above program compiles &amp; runs fine. Const keyword can be put after the variable type or before variable type. But most programmers prefer to put const ke
1 min read
“static const” vs “#define” vs “enum”
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility
4 min read
Why can't a const variable be used to define an Array's initial size in C?
What is an array? An array is a collection of items of the same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index
3 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
Difference between #define and const in C?
#define is a preprocessor directive. Data defined by the #define macro definition are preprocessed, so that your entire code can use it. This can free up space and increase compilation times.const variables are considered variables, and not macro definitions. Long story short: CONSTs are handled by the compiler, where as #DEFINEs are handled by the
2 min read
How to modify a const variable in C?
Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: "assignment of read-only variable". In the below program, a read-only variable declared using the const qualifier is tried to modify: [GFGTABS]
2 min read
Why copy constructor argument should be const in C++?
When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, pr
3 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read