Loading...

C++ Constants

This page keeps the eighteen lines from the casting page and adds two lines under them. That page ended with pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, and 1. That eighteen-line screen is the step this page builds on. The first box still holds the word pine, and the comment // the word stays pine still sits above the declarations.
This module stays on the same file. types.cpp keeps its name, its boxes, and its build command. The example adds one new box, a const int named limit, and two new writing lines that read it. The box limit is set once, at the moment it is declared, and it cannot change after that. Every line below the declaration can read limit, but no line can write to it.
Some values in a program should never change. A tax rate, a maximum number of login attempts, the number of days in a week, and the size of a game board are all values that the rest of the code relies on. If one of those values changes by accident, the bug can hide for a long time. The const keyword lets the compiler guard those values, so an accidental change becomes a build error instead of a wrong answer on the screen.

The const keyword goes in front of the type in a declaration. The line const int limit = 10; creates an int box named limit, sets it to 10, and marks it as read-only. The rest of the program can read limit as often as it likes. The value of limit is 10 on every line from that point on, because nothing can store a new value in it. A const box is still a box with a type, so limit holds an int, and the rules for int arithmetic still apply when it is read.
A const box must receive its value at the declaration. The line const int limit; with no value would create a box that can never be set, so the compiler refuses it. The first value is the only value the box will ever hold. This rule is the reason the declaration and the value sit on one line in the example. The keyword and the initial value belong together.
Reading a const box in an expression is allowed and common. The expression limit * count multiplies the read-only 10 by the ordinary int box count, which holds 2. The result is 20, and cout prints it as a plain number. The product is a new value, and it does not change limit or count. A const box can take part in as many expressions as the program needs, and it still stays at 10. The keyword also documents intent for the next reader, because the word const says that this value is not meant to change before that reader reads a single later line.

The compiler checks writes to a const box when it builds the file. A line such as limit = 5; asks to store 5 in a box that was marked read-only, and the build stops with an error. The error message names the problem, so the fix is clear: either remove the line, or make the box a normal int if the value is supposed to change. The check happens before the program runs. This early stop is the main benefit of const, because the mistake never reaches a user.
The name of a constant follows the same style as the other boxes in this file, with lowercase letters. Many C++ programs write constants in capital letters, such as MAX_SIZE, and both styles are common. This page uses the lowercase name limit so the line reads the same way as count and ratio. The style is a choice for the team, and the compiler accepts either one.

Type the file in this order, or add only the two new lines if types.cpp is already on disk. Keep the eighteen lines from the casting page. Under the double price line, add one new declaration: const int limit = 10; At the end of the writing lines, under the last cast line, add two lines: one for limit and one for limit * count. The checked file is below. The file name on disk stays types.cpp.

types.cpp adds a const limit box and two lines to the eighteen

cpp
#include <iostream>
#include <string>

int main()
{
    // the word stays pine
    std::string word = "pine";
    int count = 2;
    double ratio = 0.5;
    bool ready = true;
    double price = 7.9;
    const int limit = 10;
    std::string other = "cone";
    std::string joined = word + " " + other;
    std::cout << word << std::endl;
    std::cout << count << std::endl;
    std::cout << ratio << std::endl;
    std::cout << ready << std::endl;
    std::cout << word.size() << std::endl;
    std::cout << joined << std::endl;
    std::cout << word[0] << std::endl;
    std::cout << joined.find("cone") << std::endl;
    std::cout << joined.substr(5, 4) << std::endl;
    std::cout << count * 4 << std::endl;
    std::cout << 7 / 2 << std::endl;
    std::cout << 7.0 / 2 << std::endl;
    std::cout << (count > 1) << std::endl;
    std::cout << (count == 3) << std::endl;
    std::cout << !ready << std::endl;
    std::cout << static_cast<int>(price) << std::endl;
    std::cout << static_cast<double>(count) / 4 << std::endl;
    std::cout << static_cast<int>(ratio * 3) << std::endl;
    std::cout << limit << std::endl;
    std::cout << limit * count << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 types.cpp -o types and then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows twenty lines. The first eighteen are the same as on the casting page. The nineteenth line is limit, which prints 10. The twentieth line is limit * count, which prints 20.
Check the nineteenth line first. The const box holds 10 from its declaration, and the screen shows 10. Then check the twentieth line. The product of 10 and the box count, which holds 2, is 20. The table gives each row its piece, so compare your run with it line by line. If the screen has more than twenty lines, check that no writing line was copied twice.

📊 Two const lines and what they show

Piece What the screen shows
Fixed 10, the read-only box limit from its declaration
Product 20, limit times count, a new value that changes neither box
Rule the value is set at declaration and never changes after it
Screen pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20

Try the write that the compiler refuses. Add the line limit = 5; under the twentieth writing line, then rebuild. The build stops with an error that names the read-only box. Remove that line, rebuild, and the screen returns to twenty lines. Next, change the declaration to const int limit = 12;, and the nineteenth line becomes 12, while the twentieth becomes 24. Put the 10 back. Each experiment changes one thing, so the screen shows exactly which line caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
The next page is arrays. Its job is to store several values of the same type in one row, and to read each value by its index, which starts at 0, in the same types.cpp file. This page stops before any array. You leave with twenty lines on the screen, the constant 10, and the product 20. Count the lines before you leave. There are twenty, and the last one is 20.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top