Having two const
's for a type issues a warning / error. However if the type has been defined with typedef
, the compiler accepts it (both Visual Studio 2013 and the online compiler C++ shell).
#include <iostream> typedef const int value_type; int main() { const value_type n = 0; //ok const const int n2 = 0; //error C4114 return 0; }
Does anyone have an idea as to why? Is it that one is const (const int)
, which is different from const const int
?
The const qualifier explicitly declares a data object as something that cannot be changed. Its value is set at initialization. You cannot use const data objects in expressions requiring a modifiable lvalue. For example, a const data object cannot appear on the lefthand side of an assignment statement. C only.
In a function declaration, the keyword const may appear inside the square brackets that are used to declare an array type of a function parameter. It qualifies the pointer type to which the array type is transformed.
The const keyword can be used as a qualifier when declaring objects, types, or member functions. When qualifying an object, using const means that the object cannot be the target of an assignment, and you cannot call any of its non-const member functions.
We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value.
It's explicitly allowed in the typedef case, and disallowed in the declaration itself:
[dcl.type/1]
The type-specifiers are:
type-specifier : ... cv-qualifier
defining-type-specifier : type-specifier
[dcl.spec/1 and 2]
The specifiers that can be used in a declaration are:
decl-specifier : ... defining-type-specifier ...
Each decl-specifier shall appear at most once in a complete decl-specifier-seq, except that long may appear twice.
[dcl.type.cv/1]
There are two cv-qualifiers, const and volatile. Each cv-qualifier shall appear at most once in a cv-qualifier-seq. If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list or member-declarator-list of the declaration shall not be empty. [ Note: [basic.type.qualifier] and [dcl.fct] 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 ]
Besides type aliases, a template parameter is another case where the qualifier could be redundant. The rationale for allowing this, is to not break otherwise correct declarations just because a cv-qualifier snuck in the back door.
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