Home Theory What is the difference between char * const and const char *?

What is the difference between char * const and const char *?

by nikoo28
0 comment

Here what we are trying to learn is the difference between:-

const char *;

and

char * const;

The difference is that const char * is a pointer to a const char, while char * const is a constant pointer to a char.

const char * :- In this, the value being pointed to can’t be changed but the pointer can be.
charĀ  * const :- In this, the value being pointed at can change but the pointer can’t.

The third type is

const char * const;

which is a constant pointer to a constant char (so nothing about it can be changed).
One rule of the thumb to remember this is by reading backwards:-

  • char * const :- constant pointer to a character
  • const char * :- pointer to a constant character
  • const char * const:- constant pointer to a constant character

It will be more clear by this following example:-

#include<stdio.h>

int main()
{
    const char * p; // value cannot be changed
    char z;

	//*p = 'c'; // this will not work

	p = &z;
    printf(" %c\n",*p);
    return 0;
}

int main()
{
    char * const p; // address cannot be changed
    char z;
    *p = 'c';

	//p = &z;   // this will not work

	printf(" %c\n",*p);
    return 0;
}

int main()
{
    const char * const p; // both address and value cannot be changed
    char z;

	*p = 'c'; // this will not work
    p = &z; // this will not work

	printf(" %c\n",*p);
    return 0;
}

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More