capypad
0 day streak
cpp / beginner
Snippet

Const Correctness in C++

The const keyword declares values that cannot be changed after initialization. Use const for constants like MAX_SIZE that should never mutate. When const appears before a pointer type (const int *ptr), the data pointed to cannot be modified through that pointer. This protects against accidental modifications and helps the compiler optimize code. Const correctness is a best practice that makes code more predictable and maintainable.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
int main() {
const int MAX_SIZE = 100;
const double PI = 3.14159;
int value = 10;
const int *ptr = &value;
std::cout << "Max: " << MAX_SIZE << std::endl;
std::cout << "Value via ptr: " << *ptr << std::endl;
return 0;
}
Breakdown
1
const int MAX_SIZE = 100;
Declares a constant integer that cannot be modified
2
const double PI = 3.14159;
Declares a constant double for mathematical operations
3
const int *ptr = &value;
Pointer to const int: data cannot be changed via ptr
4
*ptr
Dereferencing a pointer-to-const to access the value