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


Pointer

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer.

const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant char.

char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

Thumb rule is to naming syntax from right to left.

// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *

Example (C)

Uncomment the commented errorneous codes and see the error.

 Live Demo

#include <stdio.h>
int main() {
   //Example: char const*
   //Note: char const* is same as const char*
   const char p = 'A';
   // q is a pointer to const char
   char const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location '*q'
   //*q = 'B';
   const char r = 'C';
   //q can point to another const char
   q = &r;
   printf("%c
", *q);    //Example: char* const    char u = 'D';    char * const t = &u;    //You can change the value    *t = 'E';    printf("%c", *t);    // Invalid asssignment    // t cannot be changed    // error: assignment of read-only variable 't'    //t = &r;    //Example: char const* const    char const* const s = &p;    // Invalid asssignment    // value of s cannot be changed    // error: assignment of read-only location '*s'    // *s = 'D';    // Invalid asssignment    // s cannot be changed    // error: assignment of read-only variable 's'    // s = &r;    return 0; }

Output

C
E

Updated on: 06-Jan-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements