capypad
0 day streak
cpp / beginner
Snippet

Constants with const: Immutable Values

The const keyword makes a variable immutable—its value cannot be changed after initialization. Constants must be initialized when declared. Attempting to modify a const variable causes a compilation error. Using const improves code clarity and prevents accidental modifications.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
#include <iostream>
 
int main() {
const int MAX_SCORE = 100;
const double PI = 3.14159;
MAX_SCORE = 200;
return 0;
}
Breakdown
1
const int MAX_SCORE = 100;
Declares an integer constant that cannot be modified after initialization
2
MAX_SCORE = 200;
This line would cause a compilation error because MAX_SCORE is const