C++ Constants

Constants are variables in C++ that, once initialised, cannot have their value modified. They offer a means of improving the readability, maintainability, and security of your code. We’ll look at the various kinds of C++ constants, their syntax, and applications in this blog.

Why Use Constants?

Constants in C++ offer the following advantages:

  • Readability: Constants facilitate comprehension of your code. Using a literal value like 1000 directly in your code is far less readable than using a constant name like MAX_LIMIT.
  • Maintainability: Rather than changing a value throughout the entire codebase, you only need to make changes to one location.
  • Preventing Errors: Constants guard against unintentional changes, which helps you stay away from tricky bugs.

Types of Constants in C++

1. Literal Constants

Literal constants are the most basic form of constants. These are values written directly into your code. For example:

int age = 30;      // '30' is a literal constant
float pi = 3.14;   // '3.14' is a literal constant
  • Integer literals: e.g., 100, -42
  • Floating-point literals: e.g., 3.14159, 2.5E3
  • Character literals: e.g., 'a', '\n'
  • String literals: e.g., "Hello", "C++"

2. const Keyword

Constants in C++ are defined using the const keyword, which prevents changes to the constant once it is declared. Since it produces a variable that remains constant during its existence, this is a more formal approach than using literal constants.

Syntax:

const data_type constant_name = value;

Example:

const int MAX_LIMIT = 100;

The MAX_LIMIT parameter in this example is set at 100 and cannot be altered.

3. constexpr Keyword

C++11 added constexpr, a declaration constructor for constants whose values are known at compile time. Const and constexpr are slightly different from one another; const can be found at runtime, whereas constexpr needs to be computed at compile time.

Syntax:

constexpr data_type constant_name = value;

Example:

constexpr int MAX_BUFFER_SIZE = 1024;

You can improve performance optimisation by ensuring that the value is a real compile-time constant by using constexpr.

4. Enumeration Constants (enum)

One technique to define a set of named integral constants is through enumerations. They are helpful when you have a collection of linked constants and make the code easier to read.

Syntax:

enum EnumName { constant1, constant2, constant3 };

Example:

enum Colors { RED, GREEN, BLUE };

By default, RED is 0, GREEN is 1, and BLUE is 2, but you can assign specific values if necessary:

enum Colors { RED = 10, GREEN = 20, BLUE = 30 };

5. #define Preprocessor Directive

Before compilation starts, constants in C++ are defined using the #define directive. Since it is a preprocessor directive, the preprocessor—rather than the compiler—handles it.

Syntax:

#define CONSTANT_NAME value

Example:

#define PI 3.14159

#define is not type-safe, in contrast to const, and during preprocessing, the value is substituted for the constant name, which may cause problems.

Learn on Youtube:
Constants in C++

When to Use Constants?

  1. When a value ought to remain constant: In order to enforce immutability, use const or constexpr.
  2. To make the code easier to read: Instead of using random magic numbers like 3.14 or 100 throughout the code, use meaningful constant names.
  3. Regarding configuration: Declaring settings such as buffer sizes, limitations, or file locations as constants facilitates easy configuration and comprehension of your program.

Best Practices for Using Constants

  • Over #define, use const or constexpr: #define is prone to errors because it lacks type safety and disregards C++ scoping rules. For the majority of cases, use const and constexpr.
  • Naming conventions: To differentiate constant names from variable names, use all capitals. For instance, PI, MAX_SIZE, etc.
  • For compile-time evaluation, use constexpr: Use constexpr to guarantee that the value is computed and optimised at compile time if you require compile-time constants.

Example: Using Constants in a C++ Program

#include <iostream>
using namespace std;

const double PI = 3.14159;
constexpr int MAX_BUFFER_SIZE = 1024;
#define APP_NAME "MyApp"

enum Direction { UP, DOWN, LEFT, RIGHT };

int main() {
    cout << "Welcome to " << APP_NAME << endl;
    cout << "Max Buffer Size: " << MAX_BUFFER_SIZE << endl;
    cout << "Pi Value: " << PI << endl;

    Direction move = UP;
    if (move == UP) {
        cout << "Moving Up!" << endl;
    }

    return 0;
}

In this example, we declare constants using const, constexpr, and #define, and we utilise an enum for instructions.

Conclusion

Writing code that is clear, effective, and free of errors in C++ requires the use of constants. Whether you use enum, const, or constexpr, they aid in error prevention, readability enhancement, and immutability enforcement. Never forget to substitute constants for magic numbers, and select the right kind depending on whether you require runtime or compile-time constants.

Learn More:
C++ Keywords

Leave a Comment