const and pointer in C++

Hello world!

This is the first post in my blog and also the first one under the topic of “C++”.

I am familiar with C and I noticed that C++ has more complex features and more widely usage. So the main purpose of the series of blogs related with C++ is to identify those advanced features(which C does not have) and remind me of them when they are needed.


Top-level const vs. Low-level const

Top-level const and low-level const have close relationships with pointers.

Supposed that a pointer in the codes points to another object, then,

Top-level const represents that the pointer is assigned to be a constant,

Low-level const represents that the object pointed by the pointer is assigned to be a constant.

int i = 0;
int *const p1 = &i;         // Top-level const, p1(the pointer) is assigned to be a constant
int j = 0;
const int *p2 = &j;         // Low-level const, the location of j(the object being pointed) is assigned to be a constant (although j is a variable)

Also, Under normal situations, Top-level const initialize any object with any data type in C++ as a constant.

const int c = 1024;         // Top-level const

If you are dealing with more complex ones.

int v = 9;
int *p = &v;
const int *const p3 = p;    // note: v and p are still assignable 

The left one is low-level const while the right one is top-level const.

p3 is a constant pointer to a constant location. No matter how you change p afterwards, p3 cannot be modified and it always points to the initial value of p (the initial location of v).

Note: The const expressions for references are low-level const.

int c = 10;
const int &d = c;           // Low-level const

Copying constants

There are some limits for low-level const when copying a constant.

No matter assigning to an object or being assigned by another object, both of them have to be assigned by low-level const expressions(The objects being pointed are constants), or the data types of them have to be convertable. Normally, A variable can be converted to a constant, but not the opposite.

A constant assigned by top-level const expression is able to assign to other objects(Of course, the constant cannot be assigned).

How auto & decltype() dealing with const expressions?

Definitions:

auto would neglect top-level const but retain low-level const.

In contrast, decltype() would retain both of them.

const int c = 10;
auto d = c; // the data type of d is <int>, not a constant
decltype(c) e = c;     // the data type of e is a constant <int>

Reference:

C++ Primer (5th Edition) by Stanley B. Lippman, Josée Lajoie, Barbara E. Moo

Advertisements