Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are top-level const qualifiers?

Tags:

c++

constants

What does const at "top level" qualifier mean in C++?

And what are other levels?

For example:

int const *i; int *const i; int const *const i; 
like image 741
user103214 Avatar asked Oct 27 '11 10:10

user103214


People also ask

What is a top-level const?

Top-level const: indicate that the pointer itself is a const. Top-level const can appear in any object type, i.e., one of the built-in arithmetic types, a class type, or a pointer type. Low-level const: a pointer that points to a const object.

What is top-level constant in C++?

As we've seen, a pointer is an object that can point to a different object. As a result, we can talk independently about whether a pointer is const and whether the objects to which it can point are const . We use the term top-level const to indicate that the pointer itself is a const .


2 Answers

A top-level const qualifier affects the object itself. Others are only relevant with pointers and references. They do not make the object const, and only prevent modification through a path using the pointer or reference. Thus:

char x; char const* p = &x; 

This is not a top-level const, and none of the objects are immutable. The expression *p cannot be used to modify x, but other expressions can be; x is not const. For that matter

*const_cast<char*>( p ) = 't' 

is legal and well defined.

But

char const x = 't'; char const* p = &x; 

This time, there is a top-level const on x, so x is immutable. No expression is allowed to change it (even if const_cast is used). The compiler may put x in read-only memory, and it may assume that the value of x never changes, regardless of what other code may do.

To give the pointer top-level const, you'd write:

char x = 't'; char *const p = &x; 

In this case, p will point to x forever; any attempt to change this is undefined behavior (and the compiler may put p in read-only memory, or assume that *p refers to x, regardless of any other code).

like image 98
James Kanze Avatar answered Oct 11 '22 20:10

James Kanze


int *const i puts const at the top-level, whereas int const *i does not.

The first says that the pointer i itself is immutable, whereas the second says that the memory the pointer points to is immutable.

Whenever const appears immediately before or after the type of the identifier, that is considered a top-level qualifier.

like image 33
Blagovest Buyukliev Avatar answered Oct 11 '22 19:10

Blagovest Buyukliev