About const

1 minute read

I sometimes fucked up with const in the past. It is better for me to summarize these fucking things.

What is the difference between the following?

const X p
X const p
const X* p
X* const p
const X* const p
const X& p
X const& p
X& const p
const X& const p

It can be easily parsed by Clockwise/Spiral rule.

const int a = 1;  // a is an integer that is const
a = 2;  // Compile error
int const a = 1;  // a is a const integer
a = 2;  // Compiler error
int a = 1;
const int* p = &a;  // OK. p is a pointer to integer that is const
// *p = 2;  // Compiler error
const int b = 2;  // b is an integer that is const
p = &b;  // OK. p is a non-const pointer
int* const q = &a;  // OK. q is a const pointer to integer
*q = 3;  // OK. q is now 3
p = q;  // OK. p now points to a const pointer q
// q = p;  // Compiler error
const int* const r = &a;  // OK. r is a const pointer to integer that is const
// *r = 2;  // Compiler error
// r = q;  // Compiler error
int a = 1;
int &b = a;  // b is a reference of an integer
b = 2;  // OK. a, b are now 2
const int& c = a;  // OK. c is a reference of an integer that is const
// c = 3;  // Compiler error
a = 3;  // OK. a, b, c, are now 3
int const& d = a;  // OK. d is a reference to const integer
// d = 4;  // Compiler error
a = 4;  // OK. a, b, c, d are now 4
/*
 * Compiler error. Fucking thing. d is a const reference to an integer.
 * Since reference is always const, it is functionally equivalent to a reference to an integer.
 * However, compiler does not allow to compile
 */
// int& const d = a;
// const int& const e = a;  // Compiler error. Same fucking thing as above