Coming Soon

This lesson is currently being developed

Constant variables (named constants)

Learn to create unchangeable named values in your programs.

Constants and Strings
Chapter
Beginner
Difficulty
35min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

5.1 — Constant variables (named constants)

In this lesson, you'll learn about constant variables in C++, why they're important, and how to use them to make your code safer and more readable.

What are constant variables?

A constant variable (also called a named constant) is a variable whose value cannot be changed after it's initialized. Once you set its value, it remains the same throughout the program's execution.

Think of constant variables like a sign that says "DO NOT CHANGE" - the value is locked in place and any attempt to modify it will result in a compiler error.

Why use constant variables?

Constants provide several important benefits:

  1. Prevent accidental modifications: Protect important values from being changed by mistake
  2. Improve readability: Give meaningful names to magic numbers and values
  3. Easier maintenance: Change a value in one place instead of throughout the code
  4. Compiler optimization: The compiler can optimize code better with constants
  5. Express intent: Clearly communicate that a value should not change

The const keyword

To create a constant variable in C++, use the const keyword:

const type variable_name = value;

Here's a basic example:

#include <iostream>

int main()
{
    const int daysInWeek = 7;
    const double pi = 3.14159;
    const char grade = 'A';
    
    std::cout << "Days in a week: " << daysInWeek << std::endl;
    std::cout << "Value of pi: " << pi << std::endl;
    std::cout << "My grade: " << grade << std::endl;
    
    return 0;
}

Output:

Days in a week: 7
Value of pi: 3.14159
My grade: A

Constants must be initialized

Unlike regular variables, constant variables must be initialized when they are declared:

❌ This won't compile:

const int x;        // Error: const variable must be initialized
x = 5;             // Can't assign to const variable later

✅ This is correct:

const int x = 5;   // Good: initialized at declaration

Constants cannot be modified

Once a constant variable is initialized, attempting to change its value will cause a compilation error:

#include <iostream>

int main()
{
    const int maxPlayers = 4;
    
    std::cout << "Maximum players: " << maxPlayers << std::endl;
    
    // This line would cause a compiler error:
    // maxPlayers = 6;  // Error: assignment to const variable
    
    return 0;
}

Practical examples of constant variables

1. Mathematical constants

#include <iostream>

int main()
{
    const double pi = 3.141592653589793;
    const double e = 2.718281828459045;
    const double goldenRatio = 1.618033988749894;
    
    double radius = 5.0;
    double area = pi * radius * radius;
    
    std::cout << "Circle area with radius " << radius << ": " << area << std::endl;
    
    return 0;
}

Output:

Circle area with radius 5: 78.5398

2. Configuration values

#include <iostream>

int main()
{
    const int maxAttempts = 3;
    const int minPasswordLength = 8;
    const double taxRate = 0.08;
    const char separator = '-';
    
    std::cout << "System Configuration:" << std::endl;
    std::cout << "Max login attempts: " << maxAttempts << std::endl;
    std::cout << "Minimum password length: " << minPasswordLength << std::endl;
    std::cout << "Tax rate: " << (taxRate * 100) << "%" << std::endl;
    std::cout << "Field separator: '" << separator << "'" << std::endl;
    
    return 0;
}

Output:

System Configuration:
Max login attempts: 3
Minimum password length: 8
Tax rate: 8%
Field separator: '-'

3. Game constants

#include <iostream>

int main()
{
    const int boardWidth = 8;
    const int boardHeight = 8;
    const int maxPlayers = 2;
    const int startingLives = 3;
    const double speedMultiplier = 1.5;
    
    std::cout << "Game Settings:" << std::endl;
    std::cout << "Board size: " << boardWidth << "x" << boardHeight << std::endl;
    std::cout << "Max players: " << maxPlayers << std::endl;
    std::cout << "Starting lives: " << startingLives << std::endl;
    std::cout << "Speed multiplier: " << speedMultiplier << "x" << std::endl;
    
    // Calculate total board squares
    const int totalSquares = boardWidth * boardHeight;
    std::cout << "Total board squares: " << totalSquares << std::endl;
    
    return 0;
}

Output:

Game Settings:
Board size: 8x8
Max players: 2
Starting lives: 3
Speed multiplier: 1.5x
Total board squares: 64

Const variables in calculations

Constant variables can be used in expressions and calculations just like regular variables:

#include <iostream>

int main()
{
    const double hourlyRate = 15.50;
    const int regularHours = 40;
    const double overtimeMultiplier = 1.5;
    
    int hoursWorked = 45;
    int overtimeHours = hoursWorked - regularHours;
    
    double regularPay = regularHours * hourlyRate;
    double overtimePay = overtimeHours * hourlyRate * overtimeMultiplier;
    double totalPay = regularPay + overtimePay;
    
    std::cout << "Pay Calculation:" << std::endl;
    std::cout << "Regular hours: " << regularHours << " at $" << hourlyRate << "/hour" << std::endl;
    std::cout << "Overtime hours: " << overtimeHours << " at $" << (hourlyRate * overtimeMultiplier) << "/hour" << std::endl;
    std::cout << "Regular pay: $" << regularPay << std::endl;
    std::cout << "Overtime pay: $" << overtimePay << std::endl;
    std::cout << "Total pay: $" << totalPay << std::endl;
    
    return 0;
}

Output:

Pay Calculation:
Regular hours: 40 at $15.5/hour
Overtime hours: 5 at $23.25/hour
Regular pay: $620
Overtime pay: $116.25
Total pay: $736.25

Constants in functions

Constants can be used as function parameters and return values:

#include <iostream>

double calculateCircleArea(const double radius)
{
    const double pi = 3.14159;
    return pi * radius * radius;
}

double calculateCircleCircumference(const double radius)
{
    const double pi = 3.14159;
    return 2 * pi * radius;
}

int main()
{
    const double radius = 7.5;
    
    double area = calculateCircleArea(radius);
    double circumference = calculateCircleCircumference(radius);
    
    std::cout << "Circle with radius " << radius << ":" << std::endl;
    std::cout << "Area: " << area << std::endl;
    std::cout << "Circumference: " << circumference << std::endl;
    
    return 0;
}

Output:

Circle with radius 7.5:
Area: 176.714
Circumference: 47.1238

Naming conventions for constants

Different coding styles use different conventions for constant names:

#include <iostream>

int main()
{
    // Common conventions:
    const int MAX_SIZE = 100;           // ALL_CAPS with underscores (traditional C style)
    const int maxSize = 100;            // camelCase (modern C++ style)
    const int kMaxSize = 100;           // k prefix (Google style)
    
    // Choose one style and be consistent throughout your project
    const double PI = 3.14159;
    const int DAYS_IN_YEAR = 365;
    const char NEWLINE = '\n';
    
    std::cout << "Maximum size: " << MAX_SIZE << std::endl;
    std::cout << "Days in year: " << DAYS_IN_YEAR << std::endl;
    
    return 0;
}

Constants vs. magic numbers

Magic numbers are hard-coded values that appear in code without explanation. Constants help eliminate magic numbers:

❌ Code with magic numbers:

#include <iostream>

int main()
{
    double price = 100.0;
    double tax = price * 0.08;        // What is 0.08?
    double discount = price * 0.15;   // What is 0.15?
    
    if (price > 50.0)                 // What is special about 50?
    {
        std::cout << "Expensive item" << std::endl;
    }
    
    return 0;
}

✅ Code with named constants:

#include <iostream>

int main()
{
    const double taxRate = 0.08;           // 8% sales tax
    const double discountRate = 0.15;      // 15% customer discount
    const double expensiveThreshold = 50.0; // Items over $50 are expensive
    
    double price = 100.0;
    double tax = price * taxRate;
    double discount = price * discountRate;
    
    if (price > expensiveThreshold)
    {
        std::cout << "Expensive item" << std::endl;
    }
    
    std::cout << "Price: $" << price << std::endl;
    std::cout << "Tax: $" << tax << std::endl;
    std::cout << "Discount: $" << discount << std::endl;
    std::cout << "Final price: $" << (price + tax - discount) << std::endl;
    
    return 0;
}

Output:

Expensive item
Price: $100
Tax: $8
Discount: $15
Final price: $93

Best practices for constant variables

  1. Use meaningful names: const int maxConnections = 10; instead of const int x = 10;

  2. Initialize at declaration: Constants must be initialized when declared

  3. Use constants for repeated values: Any value used multiple times should be a constant

  4. Group related constants: Place related constants near each other in the code

  5. Choose appropriate types: Use the most suitable data type for each constant

  6. Document complex constants: Add comments for non-obvious values

#include <iostream>

int main()
{
    // Physics constants
    const double gravityAcceleration = 9.81;      // m/s² on Earth
    const double speedOfLight = 299792458.0;      // m/s in vacuum
    
    // Application constants
    const int maxRetries = 3;                     // Maximum connection attempts
    const double timeoutSeconds = 30.0;           // Network timeout
    
    // Display formatting
    const int fieldWidth = 15;                    // Column width for output
    const char fillCharacter = '.';               // Character for padding
    
    std::cout << "Physics Constants:" << std::endl;
    std::cout << "Gravity: " << gravityAcceleration << " m/s²" << std::endl;
    std::cout << "Speed of light: " << speedOfLight << " m/s" << std::endl;
    
    return 0;
}

Summary

Constant variables are an essential feature of C++ that help create safer, more readable, and maintainable code:

  • Use the const keyword to create constant variables
  • Constants must be initialized when declared
  • Constants cannot be modified after initialization
  • Use constants to replace magic numbers and repeated values
  • Choose descriptive names for constants
  • Constants can be used in calculations and expressions just like regular variables

Constant variables are your first step toward writing more professional, maintainable C++ code.

Quiz

  1. What keyword is used to create a constant variable in C++?
  2. When must a constant variable be initialized?
  3. What happens if you try to modify a constant variable after it's been initialized?
  4. What are "magic numbers" and how do constants help eliminate them?
  5. Which of these constant declarations is correct?
    a) const int x;
    b) const int x = 5;
    c) int const x = 5;
    d) both b and c
    

Practice exercises

Try implementing these constant-related exercises:

  1. Create constants for a pizza ordering system (prices, sizes, tax rate) and calculate a total order cost
  2. Create a temperature conversion program using constants for the conversion formulas
  3. Create a simple interest calculator using constants for different interest rates
  4. Replace all magic numbers in this code with appropriate constants:
    double area = 3.14159 * 5 * 5;
    if (area > 50) {
        cout << "Large circle";
    }
    

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion