The const Keyword

Sometimes, you have a variable whose value should never change. For example, the value of Pi (π) is always ~3.14159.

The const keyword is a qualifier that declares a variable as a constant. This means its value is read-only and cannot be modified after it's initialized.

const double PI = 3.14159;

Using const is a good practice for two reasons:

  • It protects your variables from being changed accidentally.
  • It helps other developers understand that the value is not meant to be changed.

By convention, constant variable names are often written in all uppercase letters (e.g., PI, MAX_USERS).

Your Task

Let's imagine we are building a simple e-commerce site. The sales tax rate is a value that shouldn't change. In the editor, declare a constant double named TAX_RATE and assign it a value of 0.08.

🎉

Lesson Complete!

Great job! You now understand how to use constants to protect important values.

Continue to Lesson 4: Namespaces
main.cpp
Output
Click "Check Answer" to run your code.