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?
- A. The function foo() cannot change the string content pointed to by p.
- B. The function foo() cannot make the pointer p point to an address generated by malloc.
- C. The function foo() can make p point to a new string constant.
- D. The function foo() can set p to NULL.
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:
- In the foo function, it can make the p in the main function point to a new string constant.
- In the foo function, it can make the p in the main function point to NULL.
- In the foo function, it can make the p in the main function point to a memory block generated by malloc, which can be freed in main, but there will be warnings. However, even if p points to a memory block allocated by malloc in foo, you still cannot change the content pointed to by p using p[1]='x';.
- In foo, you cannot change the content of p using (*pp)[1]='x';.
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
-
-
-