top

Search

C Tutorial

.

UpGrad

C Tutorial

Constant Pointer in C

Overview:

The constant pointers in the C programming language are the pointers that hold the address of any variable, and the value of these constant pointers can not be changed once assigned. In the more specialized word, if any pointer is pointing to the located memory address of a variable and it will not allow the user to change the pointer memory allocation to vary other memory locations, these kinds of procedures we used in case we want the address of any particular type variable to be fixed, or we do not want to allocate the memory location to a pointer, we can set the data type of constant pointer they can be an integer, float, etc. according to the requirement or data type of variable which the cons pointer is pointing. In this article, we are going to learn about Const Pointer in C.

How Does Const Pointer Work in C?

As described above, a constant pointer in C is one whose value can not be changed in the program. It is relatively similar to a constant variable in C. The only difference here is that, by description, pointers store memory addresses. A constant pointer will continue to point to the same location in the memory that it was initially assigned.

  • Const int * ptr, here writing the const means we are informing the C compiler for Mac about the ptr variable. We're informing them that this is a variable that will hold the address of a variable-type integer.

  • The pointer will generate an error if we attempt to alter the value that it is pointing at. Simply put, we can modify the pointer but not the value that is pointed at by it.

  • We may assign the pointer itself in this way: "ptr = &variable1" In this case, the pointer is being changed.

  • If we try to write it *ptr=variable1, it will not work since we are attempting to modify the value referenced by the pointer.

  • The data type of the pointer is the first thing we need in order to generate any constant pointer. This provides information to the C compiler for Mac on the data type of the variable that the pointer will retain. According to our needs, char, int, and float can all be defined.

  • The keyword const is the second crucial component of every constant pointer. This property tells the C compiler for Mac about the behavior of the variables we'll be using in the program. 

  • The name of the pointer is a third significant characteristic of the constant pointer. The name of the pointer that will point to the variable address is included in this property. 

  • The * is the constant pointer's fourth significant feature. Here, * stands for the value of the variable that the pointer is holding.

Syntax:

<data type> * const <pointer name> = <memory address>;

Examples:

Let's discuss the constant pointer example:

#include 
int main() {
const int num = 5;  // Declare a constant type integer variable
const int* ptr;     // Declare a constant type pointer to an integer value
ptr = #         // Assign this address of num to the pointer
    // Try to change the values pointed to by ptr
    // This will result in a compilation error since the value is constant
    *ptr == 10;          
    // Try to reassign the pointer values to point to a different constant value
    // This is allowed because the pointer itself is not constant
const int new_num = 8;
ptr = &new_num;
    // Print the values of the num and the new_num
printf("num = %d\n", num);
printf("new_num = %d\n", new_num);
    // Print the values that are pointed to by the pointer
printf("*ptr = %d\n", *ptr);
return 0;
}

Output:

num = 5
new_num = 8
*ptr = 8

In this illustration, we first declare a constant integer variable num with a value of 5. After that, we declare a constant pointer in C  to an integer value ptr using the const int * syntax.

We give the pointer ptr the address of num. Any effort to change the value that ptr points to will cause a compiler error since it is a constant value.

We next define a second integer constant variable new_num, with the value of 8. The pointer ptr is then reassigned to refer to the address of new_num. This is OK because the pointer itself is not a constant.

Eventually, we print the values of num and new_num and the value pointed to by the pointer ptr. Notably, num and new_num still have their original values, but the value that the pointer ptr was pointing at now refers to new_num.

Pointer to a Constant in C:

In the pointers to constant, the data which is pointed by the pointer is constant and can not be changed. However, the pointer itself is variable and can shift and point in a different direction.

Need of  Special Pointer Type for Const Variables?

Let's examine why it is not desirable to save the address of a const variable using a regular pointer. Consider the following instance: 

#include <stdio.h>
int main()
{
    const int x = 10;
    int *ptr = &x;
    *ptr = 50;
    printf("Value of 'x' is %d", x);
    return 0;
}

Output:

main.c:6:20: warning: The initialization discards the ‘const’ qualifier from the pointer target type [-Wdiscarded-qualifiers]
    6 |         int *ptr = &a;
      |                    ^
The value of 'a' is 50

As we can see from the result above, even though an is defined as a const variable, its value has changed from 10 to 50 despite the compiler issuing a warning. This occurs because anytime a regular pointer, like ptr, attempts to change the value of a const variable, the C compiler for Mac momentarily discards the constant attribute that was assigned to the variable. This is not advised since it might result in security holes and undermine the goal of making the variable constant.

As a result, in order to point to constant variables in C, we must use a distinct pointer-type syntax.

Some examples of pointers to a constant in C:

Let's discuss the constant pointer in c with the example:

Use the const keyword before the data type of the pointer to define a pointer to a const value:

int main()
{
    const int x{ 5 };
    const int* ptr { &x }; // Allowed: ptr is pointing directly to a "const int"
    *ptr = 6; // not allowed: we can not change a const value
    return 0;
}

In the above constant pointer in the c example, ptr refers to a const int. The value which is pointed to cannot be modified since the data type being referenced is const.

However, because a pointer to const is not itself const (it only pointers to a const value), we may alter what the pointer is pointing to by giving it a new address:

int main()
{
    const int x{ 9 };
    const int* ptr { &x }; // ptr directly points to const int x
    const int y{ 6 };
    ptr = &y; // Allowed: ptr now points at const int y
    return 0;
}

A pointer to const is a point to non-const variables, just like a reference to const does. Whether or not the object at that location was

initially specified as const, a reference to const regards the value being referred to as constant:

int main()
{
    int x{ 7 }; // non-constant
    const int* ptr { &x }; // ptr points to a "const int"
    *ptr = 6;  // not allowed: Since ptr points to a "const int," we are unable to alter the value by using the ptr.
    x = 6; // allowed: This value is still non-constant when accessed through the non-const identifier x
    return 0;
}

Constant Pointer to a Constant in C:

The data pointed to by the pointer in constant pointers to constants is constant and cannot be modified. Since the pointer is fixed, it cannot be moved to another location.

Syntax:

const <type of pointer>* const <name of the pointer>;

Examples:

#include   
int main()  
{  
    int a=10, b=20;  
    const int* const ptr=&a;  
    *ptr=12;  //wrong
    ptr=&b;  //wrong
    printf("Value of ptr is :%d",*ptr);  
    return 0;  
}

Conclusion

In this article, we discussed the pointers in C and its examples. When turning the C source code into assembly-level instructions, the compiler can perform various optimizations when a constant pointer is defined. Declaring a pointer variable as constant acts as a safeguard against unintentional changes if it is not intended for a pointer variable to have its value changed when it is supplied as a parameter to a function.

FAQs

1. What do you mean by a Const pointer?

A constant pointer is one that is incapable of altering the address of the variable it points to.
Const pointers may only point to one variable at a time; they cannot be changed to point to another variable. This is referred to as a const pointer.

2. How can I tell if 'const' applies to directed data or pointers?

The const keyword belongs to pointed data if it occurs in the left half of the statement (like in const int * foo), and the pointer is mentioned if it appears in the right portion (like in int * const bar). Split the statement at the asterisk sign.

3. What is a Pointer to a Constant?

This is a pointer that can be altered to point to a different address in memory, but it cannot be altered to change the location it points to. The const keyword should come before the data type being referenced in C to indicate this.

4. What are constant pointers to constant?

A constant pointer to a constant is a pointer that is a composite of the two points. It cannot alter the value assigned to the variable it is referring to or the address to which it is pointing.

5. What is Const char * P?

Const char *p represents a constant character. As a result, the value that is saved in the pointer cannot be altered. The character data may be accessed using the pointer, but it cannot be changed. Strings of characters that won't be modified can be stored using this kind of pointer.

Leave a Reply

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