DEV Community

The const issue

Bastien JAUNY on October 17, 2019

TLDR: always put const AFTER the element you want to specify as constant We all love const variables and parameters. They are, well, constant. You...
Collapse
 
loki profile image
Loki Le DEV

I totally agree, by placing the const on the right side we can read from right to left:

int foo;        // integer
int const foo;  // const integer
int* foo;       // pointer to integer
int const* foo; // pointer to constant integer
int& foo;       // reference to int
int const& foo; // reference to constant int
int const* const foo; // constant pointer to constant int
int const& const foo; // constant reference to constant int    
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pgradot profile image
Pierre Gradot • Edited

int const& const foo; doesn't compile in C++.

It is impossible make a reference "points" to another variable.

A 'const reference' means that the reference considers it "points" a const object.

Collapse
 
timbeaudet profile image
🏎️Tim Beaudet🚀 • Edited

I disagree, while it does read slightly better right-to-left, which is required for determining what is const, it isn't clear. For instance in your example, you did not modify myVar, (assuming that pointer was set to the address of myVar) - but you modified the *. To me it reads much cleaner as:

const int* myVarPtr

assuming you don't want to change the value, which is 99% of the time - generally we don't care if the pointer gets modified, but the contents it points to... now that is important.

In the 1% of the time that both, or just the pointer, is important to be const, then the imo ugly:

const int* const myVarPtr;
int* const myPtr;

Will stop and make the reader / maintainer look twice. If the const was ALWAYS on the right,

int const value;
int* const valuePtr;

it is easy, very easy to slip up in maintaining or accidental writing of a const pointer to a non const value, when it should have been a pointer (const or not) to a const value.