Dan
Dan

Reputation: 2876

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?

Upvotes: 2

Views: 134

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

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;

Upvotes: 4

John Bode
John Bode

Reputation: 123458

Declaration specifiers can occur in any order. As a matter of style we tend to put storage class specifiers first, followed by type qualifiers, followed by type specifiers, as in

static const volatile unsigned long int *p;

but the compiler doesn’t care - we could write it as

unsigned long int volatile static const *p;

and the compiler will be happy with it (anyone reading and maintaining your code may not be).

The * is part of the declarator, not the declaration specifiers - it is bound to p regardless of how the declaration specifiers are ordered. If we want to declare p as a const pointer, then we must apply the const keyword as part of the declarator. To prevent confusion with declaring a pointer to const, the rule is that if we’re making the pointer const, then the const keyword goes to the right of the * operator:

const T *p;  // p is a pointer to const T
T const *p;  // same as above

T * const p; // p is a const pointer to T.

Upvotes: 1

Related Questions