Skip to content

Constants

constants

When you do not want others (or yourself) to override existing variable values, use the const keyword. This will declare the variable as "constant", which means unchangeable and read-only.

1
2
3
int a = 2;
a = 3;
std::cout << "a : " << a << '\n';

1
2
3
const int b = 3;
// b = 4; <- this fails. `b` is constant.
std::cout << "b : " << b << '\n';

1
2
3
4
// `b2` can be initialized with any value, but cannot be changed after this.
// This is possible, but makes it impossible to know b2 in compile-time.
const int b2 = a;
std::cout << "b2 : " << b2 << '\n';

1
2
3
4
// `c` can only use values available at compile-time
// `c` cannot be initialized with a mutable value
constexpr int c = 4;
std::cout << "c : " << c << '\n';

1
2
3
4
// `c` can only use values available at compile-time
// `c` cannot be initialized with a mutable value
constexpr int c = 4;
std::cout << "c : " << c << '\n';

1
2
3
// The compiler needs to know the size at compile time
// Impossible:
// std::array<int,a> v1;

1
2
3
// Sometimes possible, if b was not initialized with a mutable value
std::array<int, b> v2 = {5, 6, 5};
std::cout << "v2.size(): " << v2.size() << '\n';

1
2
// Impossible (b2 depends on a variable):
// std::array<int,b2> v2b;

1
2
3
// Always possible
std::array<int, c> v3 = {7, 8, 7, 8};
std::cout << "v3.size(): " << v3.size() << '\n';

Share Snippets