Start learning free

LESSON 13 OF 409 · VARIABLES

Const Variables in C++ in C++

Lesson Read the full explanation

There is a special type of variable in C++, which is called constant.

A constant is a variable that we do not want to change the value of during the whole program.


Creation:

You create a constant variable just like you create a normal one, but adding the keyword const before the variable's data type:

const string ourName = "AlgoCademy";

cout << ourName; // Output: AlgoCademy

Reassignment not allowed:

However, a const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you’ll get an error.

For example, this code:

const string ourName = "AlgoCademy";

ourName = "Andy"; // Here is the problem

would produce error: assignment of read-only variable 'ourName'


Must be initialized:

Constant variables must be initialized when declared. If you try to declare a const variable without a value, you’ll get an error.

For example, this code:

const string ourName;

would produce error: uninitialized const 'ourName'


Usage:

It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?

The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.

This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.

Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:

const string companyName = "Apple";
const string foundingDate = "April 1st, 1976";
const string founderName = "Steve Jobs";

Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.

I bet you wouldn't love it if a Junior Developer was able to do this successfully:

companyName = "Microsoft";
founderName = "Bill Gates";

But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.


Assignment
Follow the Coding Tutorial and let's work with constants!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    C++ · VARIABLES

    Constants in C++, explained

    Introduction

    In this lesson, we will explore the concept of constant variables in C++. Constants are a fundamental part of programming that help ensure the integrity and reliability of your code. By understanding and using constants effectively, you can prevent accidental changes to important values, making your code more robust and easier to maintain.

    Constants are particularly useful in scenarios where certain values should remain unchanged throughout the execution of a program, such as configuration settings, fixed values, or important identifiers.

    Understanding the Basics

    Before diving into the details, let's understand the basic concept of constants. A constant is a variable whose value cannot be changed once it is initialized. In C++, you declare a constant by using the const keyword before the variable's data type.

    Here is a simple example:

    const string ourName = "AlgoCademy";
    cout << ourName; // Output: AlgoCademy
    

    In this example, ourName is a constant string that holds the value "AlgoCademy". Once assigned, this value cannot be changed.

    Main Concepts

    Let's delve deeper into the key concepts and techniques related to constants in C++.

    Reassignment Not Allowed

    Once a constant variable is initialized, it cannot be reassigned. Attempting to do so will result in a compilation error. For example:

    const string ourName = "AlgoCademy";
    ourName = "Andy"; // Error: assignment of read-only variable 'ourName'
    

    This code will produce an error because we are trying to change the value of a constant variable.

    Must Be Initialized

    Constant variables must be initialized at the time of declaration. If you try to declare a constant without initializing it, you will get an error. For example:

    const string ourName; // Error: uninitialized const 'ourName'
    

    This code will produce an error because the constant variable ourName is not initialized.

    Examples and Use Cases

    Let's look at some examples and use cases where constants are beneficial.

    Example 1: Configuration Settings

    const int maxUsers = 100;
    const double pi = 3.14159;
    const string appName = "MyApp";
    

    In this example, we have defined constants for configuration settings such as the maximum number of users, the value of pi, and the application name. These values should not change during the execution of the program.

    Example 2: Fixed Values

    const int daysInWeek = 7;
    const int hoursInDay = 24;
    

    Here, we have defined constants for fixed values like the number of days in a week and the number of hours in a day. These values are universally constant and should not be modified.

    Common Pitfalls and Best Practices

    When working with constants, there are some common pitfalls to avoid and best practices to follow.

    Common Pitfalls

    • Forgetting to initialize a constant variable.
    • Attempting to reassign a constant variable.

    Best Practices

    • Always initialize constant variables at the time of declaration.
    • Use descriptive names for constants to make your code more readable.
    • Group related constants together for better organization.

    Advanced Techniques

    In addition to basic constants, C++ also supports constant expressions and constexpr variables, which are evaluated at compile time. These advanced techniques can further optimize your code.

    Constant Expressions

    constexpr int square(int x) {
        return x * x;
    }
    const int result = square(5); // result is 25
    

    In this example, the square function is a constant expression that is evaluated at compile time.

    Code Implementation

    Let's see a complete code example that demonstrates the use of constants in a real-world scenario.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    const string companyName = "Apple";
    const string foundingDate = "April 1st, 1976";
    const string founderName = "Steve Jobs";
    
    int main() {
        cout << "Company Name: " << companyName << endl;
        cout << "Founding Date: " << foundingDate << endl;
        cout << "Founder Name: " << founderName << endl;
    
        // Uncommenting the following lines will cause compilation errors
        // companyName = "Microsoft";
        // founderName = "Bill Gates";
    
        return 0;
    }
    

    This code defines constants for company information and prints them. Attempting to change these constants will result in compilation errors.

    Debugging and Testing

    When debugging code that uses constants, ensure that all constants are properly initialized and not reassigned. Writing tests for functions that use constants can help verify their correctness.

    Example Test Case

    #include <cassert>
    
    void testConstants() {
        assert(companyName == "Apple");
        assert(foundingDate == "April 1st, 1976");
        assert(founderName == "Steve Jobs");
    }
    
    int main() {
        testConstants();
        cout << "All tests passed!" << endl;
        return 0;
    }
    

    This test case verifies that the constants have the expected values.

    Thinking and Problem-Solving Tips

    When working with constants, consider the following strategies:

    • Identify values that should remain unchanged throughout the program.
    • Use constants to improve code readability and maintainability.
    • Break down complex problems into smaller parts and use constants where applicable.

    Conclusion

    In this lesson, we covered the importance of constants in C++, how to create and use them, and best practices to follow. By mastering the use of constants, you can write more reliable and maintainable code. Remember to practice and explore further applications of constants in your projects.

    Additional Resources

    For further reading and practice problems, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free