const Pointer in C

A const pointer in C refers to a pointer that points to a constant value. This means that the value stored at the address the pointer is pointing to cannot be changed through that pointer. However, the pointer itself can be changed to point to a different memory address.

Definition

A const pointer is a pointer that holds the address of a value that cannot be modified through the pointer. The pointer itself can point to a different address, but the value it points to cannot be changed using this pointer.

The syntax for declaring a constant pointer in C is as follows:

Syntax:

                        
data_type *const pointer_name;
                        
                    

Example: Constant Pointer

This example demonstrates the use of a constant pointer. The pointer itself is constant, meaning you cannot change the address it points to, but you can modify the value stored at that address.

Example Code:

                        
#include <stdio.h>
int main() 
{
    int num = 10;
    int *const ptr = #  // Constant pointer
        
    printf("Value pointed to by ptr: %d\n", *ptr);
        
    // Modify the value pointed to by ptr
    *ptr = 20;
        
    printf("Modified value: %d\n", *ptr);
        
    // Attempting to change the pointer's address will cause a compile-time error
    // ptr = &num2;  // Error: cannot change address of constant pointer
        
    return 0;
}
                        
                    

Output

Value pointed to by ptr: 10
Modified value: 20

Key Points