How does const work with pointers?

In C, the const keyword can be used with pointers in two main ways, affecting either the pointer itself or the data it points to. Here’s how it works:

  1. Pointer to Constant Data: When you declare a pointer to a constant type, it means that the data being pointed to cannot be modified through that pointer.

    const int *ptr;

    In this case, ptr is a pointer to an int that is constant. You can change the pointer to point to another integer, but you cannot change the value of the integer it points to through ptr.

    int a = 10;
    int b = 20;
    ptr = &a; // Valid
    // *ptr = 15; // Error: cannot modify the value pointed to by ptr
    ptr = &b; // Valid: ptr can point to another integer
  2. Constant Pointer: When you declare a constant pointer, it means that the pointer itself cannot be changed to point to another address, but the data it points to can be modified.

    int *const ptr;

    In this case, ptr is a constant pointer to an int. You cannot change where ptr points, but you can change the value at that address.

    int a = 10;
    ptr = &a; // This must be done at the time of declaration
    *ptr = 15; // Valid: you can modify the value pointed to by ptr
    // ptr = &b; // Error: cannot change the address stored in ptr
  3. Constant Pointer to Constant Data: You can also combine both concepts, creating a constant pointer to constant data.

    const int *const ptr;

    In this case, neither the pointer can be changed to point to another address, nor can the data it points to be modified.

    int a = 10;
    ptr = &a; // This must be done at the time of declaration
    // *ptr = 15; // Error: cannot modify the value pointed to by ptr
    // ptr = &b; // Error: cannot change the address stored in ptr

Using const with pointers helps to enforce better coding practices by preventing unintended modifications to data and improving code safety.

0 Comments

no data
Be the first to share your comment!