Const Qualifier In C https://www.skillvertex.com/blog Fri, 10 May 2024 06:52:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png Const Qualifier In C https://www.skillvertex.com/blog 32 32 Const Qualifier In C https://www.skillvertex.com/blog/const-qualifier-in-c/ https://www.skillvertex.com/blog/const-qualifier-in-c/#respond Fri, 10 May 2024 06:52:10 +0000 https://www.skillvertex.com/blog/?p=1870 Read more]]>

Table of Contents

Const Qualifier In C

In C programming, there’s something called the “const” qualifier. It’s like a rule that says once you set a value to something, you can’t change it. This is really important because it helps make sure data in a program stays reliable and doesn’t get messed up accidentally. In this discussion about “const” in C, we’ll look at how to use it and why it’s useful for C programmers. Knowing about “const” is a big part of writing code in C that’s strong and easy to understand.

What is a Const Qualifier

You can use the “const” qualifier in C to declare a variable and make sure it doesn’t change its value. However, it’s important to note that, depending on where the const variable is stored, you might still be able to change its value using a pointer, but this isn’t recommended.

Using “const” in C is a good idea when you want to make sure certain values stay the same and don’t get accidentally changed. It’s a way to keep your code reliable and prevent unexpected modifications.

1. Constant Variables

const int var = 100;

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

// 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;

You can modify a pointer to point to a different integer variable, but you can’t change the value of the actual object (the thing it’s pointing to) using that pointer. The pointer itself is stored in an area where you can read and write data, like the stack. Refer to the example below:

// 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 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;
}

In C++ and C, down qualification is not allowed and can lead to issues or warnings. Down qualification occurs when you assign a qualified type (e.g., const-qualified) to a non-qualified type. This means that if you have a pointer or reference to a const-qualified object and you try to assign it to a non-const pointer or reference, it will likely result in a compilation error in C++

Example 3: Program to show down qualifications


// 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 declaration you provided is for a pointer to a constant integer, not a constant pointer to an integer. In C and C++, these two declarations have different meanings


// 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 Qualifier In C

Using the const keyword in your code offers several advantages:

  1. Improved Code Readability: When you mark a variable as const, you’re telling other programmers that its value shouldn’t change. This makes your code easier for others to understand and maintain.
  2. Enhanced Type Safety: By using, you can prevent accidental modifications to values, reducing the chances of bugs and errors in your code. It adds an extra layer of protection.
  3. Improved Optimization: Compilers can optimize const variables more effectively because they know these values won’t change during program execution. This optimization can result in faster and more efficient code.
  4. Better Memory Usage: Declaring variables as const can often eliminate the need to create unnecessary copies of values, reducing memory usage and improving overall performance.
  5. Improved Compatibility: Using const in your code can enhance compatibility with other libraries and APIs that also use const variables. It helps ensure that your code plays well with others.
  6. Improved Reliability: const helps make your code more reliable by preventing unexpected value modifications, and reducing the risk of bugs and errors in your program.

In summary, incorporating the const keyword in your code can lead to more readable, reliable, and optimized software while enhancing compatibility with other code and libraries.

FAQ – Const Qualifier In C

Q1. What is the const qualifier?

Ans. The const qualifier serves as a clear declaration that a data object’s value cannot be changed once it’s initialized. In other words, it’s a way of saying, “This thing won’t change after I set its value.” This means you can’t use const data objects in situations where a change is expected or required. For example, you can’t use a const data object on the left side of an assignment statement because it’s not allowed to be modified once it has a value.

Q2. Why do we require const qualifier in C with example?

Ans. The const qualifier designates a variable as unchangeable after initialization. This is valuable for constants like PI, enhancing code readability and preventing errors.

Q3. What is const and volatile qualifier in C?

Ans. The const keyword ensures a pointer can’t change after initialization, protecting it from modification. In contrast, the volatile keyword indicates that a value can be changed by external actions beyond the user’s control.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/const-qualifier-in-c/feed/ 0