Pointer to Constant in C

Pointer to Constant in C

In this article, I am going to discuss Pointer to constant in C with Examples. Please read our previous articles, where we discussed Character Pointer in C.

Pointer to Constant in C Language:

The pointer will point to an address, where it cannot change the value at that address. But this pointer can point to some other address. Assigning values is not possible in the pointer to constant. The pointer value can be incremented or decremented. The pointer is pointing to the constant data objects.

Syntax: const <pointer-type> * <pointer-name>;
Example: const int*p;

Program:
#include<stdio.h>
int main ()
{
    int a = 10, b = 20;
    const int *p;
    p = &a;
    printf ("value of a is %d, *p is %d \n", a, *p);
    *p = 5;		//wrong you can not change value at address
    printf ("value of a is %d, *p is %d \n", a, *p);
    p = &b;		//you can change address
    return 0;
}

Output:

Pointer to Constant in C Language

Constant Pointer in C:

The pointer will point to one address which we initialize at declaration time. After that, we cannot change that address. But the value at that address we can change. We can assign a value to a constant pointer. Values cannot be incremented or decremented. Constant Pointer points to the data object.

Syntax: const <pointer-type> * const <pointer-name> = <memory-address>;
Example: const int*const p=&a;

Program:
#include<stdio.h>
int main ()
{
    int a = 10, b = 20;
    int *const p = &a;
    printf ("value of a is %d, *p is %d \n ", a, *p);
    *p = 5;		//changing value at address
    printf ("value of a is %d, *p is %d \n ", a, *p);
    p = &b;		//changing address wrong
    return 0;
}

Output:

Constant Pointer in C

In the next article, I am going to discuss Null Pointer in C language. Here, in this article, I try to explain Pointer to constant in C. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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