Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler doesn't give error when typedef const pointer is used with extra const?

Following gives error as expected:

int* const const p = new int; // g++ error: duplicate cv-qualifier

But below doesn't give any error, even though it's equivalent to above one:

typedef int* const intp_const;
intp_const const p = new int;  // ok !
        // ^^^^^ duplicate ?

Why does compiler ignores the extra const ?

[Note: intp_const const is not same as const char* const, because *p = <value>; is possible.]

like image 537
iammilind Avatar asked Jul 18 '12 04:07

iammilind


People also ask

When should you use const c++?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).

How do you declare a const pointer in C++?

Pointers with Const Memory Address Pointers with a constant memory address are declared by including the const after the *. Because the address is const, the pointer must be assigned a value immediately.

Which of the following is the correct declaration for constant pointer to an int data type?

int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer.

When to const?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.


2 Answers

In 7.1.5 [dcl.type] (C++03), it is stated that redundant cv-qualifiers are allowed when introduced through a typedef:

const or volatile can be combined with any other type-specifier. However, redundant cv- qualifiers are prohibited except when introduced through the use of typedefs (7.1.3) or template type arguments (14.3), in which case the redundant cv-qualifiers are ignored.

like image 141
Daniel Fischer Avatar answered Oct 23 '22 05:10

Daniel Fischer


7.1.6 p 2 forbids the use of multiple const in the same decl-specifier-seq

As a general rule, at most one type-specifier is allowed in the complete decl-specifier-seq of a declaration or in a type-specifier-seq or trailing-type-specifier-seq. The only exceptions to this rule are the following:

— const can be combined with any type specifier except itself.

7.1.6.1 p 1 allows the use through the typedef:

There are two cv-qualifiers, const and volatile. If a cv-qualifier appears in a decl-specifier-seq, the init- declarator-list of the declaration shall not be empty. [ Note: 3.9.3 and 8.3.5 describe how cv-qualifiers affect object and function types. — end note ] Redundant cv-qualifications are ignored. [ Note: For example, these could be introduced by typedefs. — end note ]

like image 38
David Rodríguez - dribeas Avatar answered Oct 23 '22 06:10

David Rodríguez - dribeas