C++ Constant

In C++, a constant is a variable whose value cannot be changed after it is initialized. Once a constant is set, you cannot modify its value throughout the program. Constants are useful when you want to ensure that a certain value stays the same and doesn’t get accidentally modified.

In C++, you can define constants using the const keyword or #define preprocessor directive.

Using the const keyword:


#include <iostream>
using namespace std;

int main() {
    const int MAX_SPEED = 180;  // constant integer
    cout << "Car's maximum speed is: " << MAX_SPEED << endl;

    // Uncommenting the next line will cause a compile-time error:
    // MAX_SPEED = 150;  // Error! Cannot modify a constant value

    return 0;
}

Explanation:

  1. MAX_SPEED is a constant that holds the value 180.
  2. The const keyword ensures that the value of MAX_SPEED cannot be changed after initialization.

Output:

Car's maximum speed is: 180

Using #define Preprocessor Directive:


#include <iostream>
using namespace std;

#define MAX_SPEED 180  // Defining a constant using #define

int main() {
    cout << "Car's maximum speed is: " << MAX_SPEED << endl;

    // You can't modify MAX_SPEED, as it's a constant
    // Uncommenting the next line will cause a compile-time error:
    // MAX_SPEED = 150;  // Error!

    return 0;
}

Explanation:

  1. define MAX_SPEED 180 creates a constant MAX_SPEED with the value 180.
  2. define is a preprocessor directive and is replaced at compile time, so it works a bit differently than const.

Output:

Car's maximum speed is: 180

Why Use Constants?

Safety: Constants prevent accidental changes to important values.

Clarity: By using meaningful names for constants, you make your code more readable and self-documenting.

Maintainability: If you need to change the value of a constant, you only have to change it in one place, rather than hunting for all instances where it’s used.