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 ?
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.
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With