static const
- C++ course
- Intermediate
- Lesson 32/116
- 5 min
Learn to define class constants with static const.
static const
A static const member is an immutable constant at the class level. Integral types (int, char, bool) can be initialized directly inside the class body.
Example: static const int MAX = 100;. This requires no separate outside definition. More complex types still need an outside definition. static const members can be used as compile-time constants: as array sizes or case labels. The value cannot be changed later, making them suitable for configuration constants.
Using static const
Because static const members are compile-time constants, they can be used as array sizes: int data[MAX];. This is ideal for values that will not change at runtime.
For example, in a Config class you can define static const int MAX_USERS = 50; and write int users[MAX_USERS];. Modern C++ also offers constexpr, but static const is still common and compatible. It guarantees the constant cannot be modified.
Practice Add a static const to the Config class
Define a Config class. Under public: add static const int MAX = 5;. In main declare an array int data[Config::MAX]; and write std::cout << Config::MAX;.
Starter code
#include <iostream>
// Define the Config class here
int main() {
// Declare an array with the constant and print it
return 0;
}Sample solution
#include <iostream>
class Config {
public:
static const int MAX = 5;
};
int main() {
int data[Config::MAX];
std::cout << Config::MAX;
return 0;
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which can be initialized inside the class?
class Config { ??? };- static int max = 100;
- static const int MAX = 100; Correct answer
- const int max;
- int max = 100;
Explanation: A static const integer can be initialized inside the class.
2 Match each declaration to its type
| Term | Meaning |
|---|---|
static const int MAX = 100; |
In-class constant |
MAX |
Compile-time constant |
static int count; |
Modifiable |
const int x; |
Instance constant |
3 Complete the constant value
class Config { public: static const int MAX = ____; };
class Config { public: static const int MAX = 100; };
Explanation: The integer constant takes the value 100.