const
KeywordSometimes, 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:
By convention, constant variable names are often written in all uppercase letters (e.g., PI
, MAX_USERS
).
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
.
Click "Check Answer" to run your code.