cpointersconstants

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 ?


Solution

  • 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.