Pointers and Constants in C (const int * & int* const difference)

As we already know, C pointers handle with addresses of any variables in the program. Here if we think of making constants, we need to think of it as two types.

  1. Making values in the address as constants.
  2. Making addresses itself as constants.

const int* a

Here this line of code makes values in the pointer as constants. Whereas we can change the addresses assigned pointer.

const int* ptr;

In the above image “ptr” pointer can changes its addresses from 0xfc to 0xab. Whereas it can’t change any values stored in these addresses.

int main() {
    const int *a;   // Constant value, value cann't be changed here.
    int b = 30;
    int c = 20;
    a = &b; // 30
    *a = 20;    // compile time error, read-only value.
    printf("%d\n", *a);
    return 0;
}

*a = 20, gives an error here as *a is a constants and can’t change its values.

int* const a

The above line of code makes pointer “a” as constant, whereas we can change the values inside the address stored in the pointer.

int* const ptr;

Here in the above diagram, ptr holds an address 0xfc. “ptr” can’t change its address here as it is read-only, whereas the values in the address 0xfc can be changes using *ptr.

int main() {
    int b = 30;
    int c = 20;
    int* const a = &b;
    
    a = &c; // Compile time error, ready-only address.
    *a = 20; // Works here.
    return 0;
}

Changing the value from 30 to 20 using “*a” works without any error, but when we try to assign another address to a like “a=&c” it gives a compile-time error.

These are two types of constant pointers in C programming. If you have any better examples, please let our readers know by commenting here below.