C++ Constants


Introduction

In C++, constants are variables whose values cannot be changed once they are initialized. They are a crucial part of writing reliable and maintainable code because they provide guarantees that certain values remain constant throughout the execution of the program. Using constants can help improve code readability and reduce errors that might occur when values are accidentally modified.

This post will cover the following:

  • Declaring Constants in C++
  • const Keyword
  • constexpr Keyword
  • Literal Constants
  • Advantages of Using Constants

1. Declaring Constants in C++

In C++, constants are typically declared using the const or constexpr keyword. These keywords ensure that the variable is treated as a constant, meaning its value cannot be modified after it is initialized.

1.1 const Keyword

The const keyword is used to define variables whose value is set at initialization and cannot be changed later. This applies to all types of variables (primitive types, objects, arrays, etc.).

Syntax:
const data_type variable_name = value;

Example:

#include <iostream>
using namespace std;

int main() {
    const int MAX_SIZE = 100;  // Constant integer
    cout << "Maximum Size: " << MAX_SIZE << endl;
    
    // Uncommenting the following line would cause an error
    // MAX_SIZE = 200;  // Error: cannot assign to a const variable

    return 0;
}

In this example, MAX_SIZE is declared as a constant integer with the value 100. Attempting to modify it later in the code would result in a compile-time error.

Key Points:

  • Once a const variable is assigned a value, it cannot be modified.
  • const variables can be initialized at the time of declaration.

2. constexpr Keyword

The constexpr keyword was introduced in C++11 and ensures that the value of a variable is known at compile-time. This makes it ideal for situations where the value is required to be constant during compilation, such as when initializing array sizes or performing certain calculations at compile-time.

Syntax:

constexpr data_type variable_name = value;

Example:

#include <iostream>
using namespace std;

constexpr int getSquare(int n) {
    return n * n;
}

int main() {
    constexpr int num = 5;
    constexpr int square = getSquare(num);  // Evaluated at compile time

    cout << "Square of " << num << " is: " << square << endl;

    return 0;
}

In this example, the value of square is computed during compilation because num and getSquare(num) are both marked as constexpr. This can improve performance by reducing runtime overhead.

Key Points:

  • constexpr variables must have their values known at compile-time.
  • Functions marked with constexpr can also be evaluated at compile-time if they meet certain conditions (e.g., the function's arguments must be constant expressions).

3. Literal Constants

Literal constants are fixed values that are embedded directly into the program code. These include integers, floating-point numbers, characters, and strings. Literal constants do not require a variable declaration and cannot be changed during program execution.

Example:

#include <iostream>
using namespace std;

int main() {
    cout << "Integer Literal: " << 42 << endl;      // Integer constant
    cout << "Float Literal: " << 3.14f << endl;     // Floating-point constant
    cout << "Char Literal: " << 'A' << endl;        // Character constant
    cout << "String Literal: " << "Hello, World!" << endl;  // String constant

    return 0;
}

Key Points:

  • Literal constants are values that appear directly in the program code.
  • You cannot modify literal constants.

4. Advantages of Using Constants

There are several advantages to using constants in C++ programs:

4.1 Improved Code Safety

Using constants ensures that certain values cannot be accidentally changed during the program’s execution. This reduces the risk of bugs that can arise from modifying values that should remain fixed.

4.2 Better Code Readability

Constants make the intent of the code clearer. For example, if you use a constant to represent the maximum size of an array, it’s easy for a reader of the code to understand its purpose compared to using a magic number.

Example:
const int MAX_HEIGHT = 500;

This is much clearer than simply using 500 directly in the code.

4.3 Easier Code Maintenance

If you need to change a constant value (e.g., the maximum size or the tax rate), you only need to modify it in one place in the code. This makes your code easier to maintain.

4.4 Optimize Performance

In some cases, using constexpr can allow the compiler to optimize your code better, since the value is known at compile-time. For example, it can be used in array sizes, template parameters, or when precomputing values.


5. Constant Pointers and Pointer to Constants

In C++, you can also declare constant pointers and pointers to constants.

5.1 Constant Pointers

A constant pointer is a pointer whose value cannot be changed, i.e., the address it points to cannot be modified, but the content at that address can be changed.

Example:
int num = 5;
int* const ptr = &num;  // Constant pointer

*ptr = 10;  // Allowed: modifying the value at the address
// ptr = &anotherVar;  // Error: cannot change the pointer's address

5.2 Pointer to Constant

A pointer to a constant is a pointer that can point to different addresses, but the value at the address cannot be modified.

Example:
const int num = 5;
const int* ptr = &num;  // Pointer to constant

// *ptr = 10;  // Error: cannot modify the value at the address
ptr = &anotherVar;  // Allowed: changing the pointer's address

Key Points:

  • Constant Pointer: The pointer's address cannot change, but the data it points to can.
  • Pointer to Constant: The pointer’s address can change, but the data it points to cannot be modified.