cconstantsdeclarationqualifiers

Why is there 2 ways to write a Pointer to Constant, but only one way to write Constant Pointers?


A Pointer to Constant can be written in either these two ways:

int a = 5;

const int* b = &a;
/* or */
int const* c = &a;

But a Constant Pointer can only be written in this way:

int a = 5;

int* const b = &a;

// const* int c = &a; This will not compile.

The second line will create this error:

expected identifier or '(' before 'int'

Why is this not allowed?


Solution

  • In C declaration is defined the following way

    declaration:
        declaration-specifiers init-declarator-list
    

    For example in this declaration

    const int* b = &a;
    

    const int are type specifiers and ( *b ) = &a is the init-declarator-list.

    You may rewrite the above declaration like

    const int ( *b ) = &a;
    

    If you want to make the declarator a constant object you should to write

    const int ( * const b ) = &a;
    

    You may not separate a declarator using a type specifier (except using a qualifier) like

    const* int c = &a;
    

    That is in this record the type specifier int splits the declarator *c.

    On the other hand, you could introduce a type specifier the following way

    typedef const int *Ptr;
    

    In this case you can make the declarator constant writing

    const Ptr b = &a;
    

    In this case you will get the same declaration as

    const int * const b = &a;