your image

Difference between const char *p, char * const p and const char * const p - GeeksforGeeks

geeksforgeeks
Related Topic
:- C language programming languages

Difference between const char *p, char * const p and const char * const p

  • Difficulty Level : Easy
  • Last Updated : 09 Oct, 2018

Prerequisite: Pointers
There is a lot of confusion when char, const, *, p are all used in different permutaions and meanings change according to which is placed where. Following article focus on differentiation and usage of all of these.

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed. const keyword applies to whatever is immediately to its left. If there is nothing to its left, it applies to whatever is immediately to its right.

  1. const char *ptr : This is a pointer to a constant character. You cannot change the value pointed by ptr, but you can change the pointer itself. “const char *” is a (non-const) pointer to a const char.

     

     

     

    // C program to illustrate 

    // char const *p

    #include<stdio.h>

    #include<stdlib.h>

      

    int main()

    {

        char a ='A', b ='B';

        const char *ptr = &a;

          

        //*ptr = b; illegal statement (assignment of read-only location *ptr)

          

        // ptr can be changed

        printf( "value pointed to by ptr: %c\n", *ptr);

        ptr = &b;

        printf( "value pointed to by ptr: %c\n", *ptr);

    }

    Output:

    value pointed to by ptr:Avalue pointed to by ptr:B

    NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of ‘*'(asterik) is also same.

  2. char *const ptr : This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by ptr.

     

     

     

    // C program to illustrate 

    // char* const p

    #include<stdio.h>

    #include<stdlib.h>

      

    int main()

    {

        char a ='A', b ='B';

        char *const ptr = &a;

        printf( "Value pointed to by ptr: %c\n", *ptr);

        printf( "Address ptr is pointing to: %d\n\n", ptr);

      

        //ptr = &b; illegal statement (assignment of read-only variable ptr)

      

        // changing the value at the address ptr is pointing to

        *ptr = b; 

        printf( "Value pointed to by ptr: %c\n", *ptr);

        printf( "Address ptr is pointing to: %d\n", ptr);

    }

    Output:

    Value pointed to by ptr: AAddress ptr is pointing to: -1443150762Value pointed to by ptr: BAddress ptr is pointing to: -1443150762

Comments