Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the non-const pointer being treated as a const when using typedef?

typedef char* c;
const c ptr1 = "pointer";
++ptr1; /// error
const char* ptr2 = "pointer";
++ptr2; /// runs fine

Now ptr1 should be of type const char* and thus a non-const pointer, then why is it being treated as a constant pointer ?

like image 587
cirronimbo Avatar asked Aug 08 '12 12:08

cirronimbo


People also ask

Is a non const pointer that points to a constant value?

A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.

Can function pointers be const?

Pointers can be declared as pointing to mutable (non-const) data or pointer to constant data. Pointers can be defined to point to a function. My coworkers and I were discussing the use of "const" with pointers and the question came up regarding the use of const with function pointers.

Can const pointers be null?

The null pointer constant is guaranteed not to point to any real object. You can assign it to any pointer variable since it has type void * . The preferred way to write a null pointer constant is with NULL .

Can a const pointer be modified?

const int * is a pointer to an integer constant. That means, the integer value that it is pointing at cannot be changed using that pointer.


2 Answers

They are not the same.

The first designates a const-pointer-to-char, the second is a pointer-to-const-char.

Try reading right to left:

const char *p;  // p is a pointer to char which is const
char const *p;  // p is a pointer to const char (same as previous)
char * const p; // p is a const pointer to char
char const * const p; // p is a const pointer to const char

By using the typedef typedef char* c you pack the meaning "pointer to char" into a single alias c:

const c p; // p is a const [c] --> p is a const [pointer to char]

Additional explanations:

Typedefs are not in-place-expanded like macros are, i.e.

const c p;

really becomes

const [char*] p;

it does not become

const char* p; // Nope.

Don't expand it like macros in your mind, with the typedefs, you've bound char and * together and formed an atom.

like image 81
Sebastian Mach Avatar answered Oct 20 '22 18:10

Sebastian Mach


ptr1 is a const (char *), meaning the pointer itself is a const, whereas ptr2 is a (const char) *, meaning the target of the pointer is const.

like image 3
chmeee Avatar answered Oct 20 '22 18:10

chmeee