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.]
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).
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.
int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With