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 ?
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 ?
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.
c
is not expanded; typedef
isn't a textual macro facility. Or, to look at it another way, it implicitly puts parens around the type, so const c
is const (char*)
rather than (const char)*
. –
Catalogue 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.
it has to do with the way that c groups things internally. A typedef isn't like a macro, it doesn't just substitute things in. If you were to pus parenthesis in it would look like this.
const (char*) ptr1 = "pointer";
(const char)* ptr2 = "pointer";
Writing it like:
typedef char* c;
c const ptr1 = "pointer";
++ptr1; /// error
char const* ptr2 = "pointer";
++ptr2; /// runs fine
makes the difference more visible, and this should be the same as your example
You need a new typedef
for the const
variable one, like so:
typedef char* c;
typedef const char* const_c;
const_c ptr1 = "pointer";
++ptr1; /// runs fine
const char* ptr2 = "pointer";
++ptr2; /// runs fine
Now ptr1 and ptr2 work just the same way, including implicit casting!
const c ptr1
the const
applies to a pointer, but with const char *
the const
applies to a char
. –
Bays const char *
, they were asking why the application of const
to a type alias didn't work as expected. –
Bays © 2022 - 2024 — McMap. All rights reserved.
typedef char* c
andtypedef const char* const_c
, nowconst_c
works likeptr2
and you just need to useconst_c
instead ofc
whenever*c
is intended to beconst
! – Grove