Menu
Coddy logo textTech

Constants

Part of the Fundamentals section of Coddy's C++ journey — lesson 10 of 74.

A constant is a special type of variable that cannot be changed once it is initialized.

To declare a constant use the keyword const followed by the variable type:

const int maxValue = 100;

In the above example, a constant named maxValue is initialized with the value 100.

If we try to change a constant value:

const int maxValue = 100;
maxValue = 200; // This will cause an error

It will result in an error because constant values cannot be changed.

In C++, it is a common convention to name constants using ALL_CAPS (uppercase letters with underscores between words):

const int MAX_VALUE = 100;
const double PI = 3.14159;

This makes constants easy to distinguish from regular variables in your code.

challenge icon

Challenge

Beginner

Create a constant named PI and initialize it with the value 3.14159.

Cheat sheet

A constant cannot be changed after initialization. Use const followed by the type:

const int MAX_VALUE = 100;
const double PI = 3.14159;

By convention, constants are named in ALL_CAPS. Attempting to modify a constant causes an error:

MAX_VALUE = 200; // Error - cannot change constant value

Try it yourself

#include <iostream>

int main() {
    // Type your code below


    // Don't change the line below
    std::cout << "PI = " << PI;
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals