Easy Tutorial
❮ Java Polymorphism Java Annotation ❯

Differences between const char, char const, and char* const

Category Programming Technology

Bjarne Stroustrup, in The C++ Programming Language, provides a mnemonic method: read a declaration from right to left.

char * const cp; ( * read as pointer to ) 
cp is a const pointer to char 

const char * p; 
p is a pointer to const char; 

char const * p;

Similarly, since C++ does not have a const* operator, const can only belong to the preceding type.

The C++ standard specifies that placing the const keyword before the type or the variable name is equivalent.

const int n=5;    //same as below
int const m=10;

const int *p;    //same as below  const (int) * p
int const *q;    // (int) const *p

char ** p1; 
//    pointer to    pointer to    char 
const char **p2;
//    pointer to    pointer to const char 
char * const * p3;
//    pointer to const pointer to    char 
const char * const * p4;
//    pointer to const pointer to const char 
char ** const p5;
// const pointer to    pointer to    char 
const char ** const p6;
// const pointer to    pointer to const char 
char * const * const p7;
// const pointer to const pointer to    char 
const char * const * const p8;
// const pointer to const pointer to const char

Here, we can look at a previous Google笔试 question:

const char *p="hello";       
foo(&p);  // function foo(const char **pp) which statement is correct?

The answer to this question is controversial. For the above question, we can test it with the following program:

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
void foo(const char **pp)
{
//    *pp=NULL;
//    *pp="Hello world!";
        *pp = (char *) malloc(10);
        snprintf(*pp, 10, "hi google!");
//       (*pp)[1] = 'x';
}
int
main()
{
    const char *p="hello";
    printf("before foo %s/n",p);
    foo(&p);
    printf("after foo %s/n",p);
    p[1] = 'x';
    return;
}

Conclusions:

Therefore, it seems that gcc only restricts based on the literal meaning of const, i.e., for a const char* p pointer, regardless of whether p later points to memory allocated by malloc or constant memory, you cannot change its content using p[1]='x';. However, it is strange that in foo, after p points to memory allocated by malloc, you can modify its content using functions like snprintf.

** Click to Share Notes

Cancel

-

-

-

❮ Java Polymorphism Java Annotation ❯