C++ Constants

In C++, constants are values that remain unchangeable throughout the program. If a value should stay the same such as fixed rates or system limits—it should be declared as a constant using the const keyword.

Tutorials dojo strip



Declaring a Constant Variable

To prevent a variable’s value from being modified, use const before the type:

Example

C++

Explanation:

  • maxSpeed is set as a constant, meaning it cannot be changed later.
  • Trying to assign a new value causes an error.




When to Use Constants

If a value should never change, always declare it as a constant to avoid accidental modifications.

Example

C++

This ensures the value always remains 24 throughout the program.




Important Notes About Constants

  • A constant must be assigned a value at declaration:
C++

  • This will not work (causes an error):
C++

Tutorials dojo strip