Pointers/Memory Allocation   «Prev  Next»
Lesson 2 The const keyword
Objective Examine the use of the keyword const.

C++ const Keyword

The const keyword in C++ has significant value and plays a vital role in enhancing the safety, efficiency, and readability of your code. It is used to declare that an object has a constant value, which means that once the value is set, it can't be altered.
  1. Constant Variables: When you declare a variable as const, it means that the variable's value is constant and cannot be changed after it is initialized. Trying to modify a const variable will lead to a compile-time error. For example:
    const int x = 10;
    x = 20;  // Compiler error, attempting to modify a const variable
    
  2. Constant Pointers: The const keyword can also be used with pointers in two ways: a pointer to a const object (the object pointed to can't be changed) and a const pointer (the address held by the pointer can't be changed).
    const int* ptr1;  // Pointer to a const int, the int can't be changed via ptr1
    int* const ptr2;  // Const pointer to an int, the address ptr2 points to can't be changed
    
  3. Constant Functions: When a member function of a class is declared as const, it means that the function is not allowed to modify any member variables of the class (unless they are declared mutable). This is especially useful when dealing with objects that should not be modified, such as when passing an object of the class by constant reference. For instance:
    class MyClass {
    public:
        int getValue() const {  // This function can't modify any member variables
            return value;
        }
    private:
        int value;
    };
    
  4. Constant Parameters: const is also used to prevent changes to function parameters passed by reference or pointer, to ensure the function doesn't modify the original argument.
    void myFunc(const int& param) {
        // param can't be changed inside this function
    }
    

By using the const keyword appropriately, you can make your C++ code safer (by preventing unwanted side effects), clearer (by making your intentions explicit), and more efficient (by allowing the compiler to make certain optimizations).


As we saw in a previous module, the keyword const is a type specifier. When used alone in a declaration, the base type is implicitly int. A variable declared as const cannot have its value changed. A const variable can be used in places that otherwise would require a literal, such as an array size.

const and lvalue

When an ordinary variable is used on the left side of an assignment, it is used as an lvalue. An lvalue is an expression that can be used as an address to be stored into. A const variable cannot be used on the left side of an assignment. It is a nonmodifiable lvalue. This implies that a const variable must be initialized where defined.

Specifying Integer Constants

Because you can have different types of integer variables, you might expect to have different kinds of integer constants. If you just write the integer value 100, for example, this will be of type int. If you want to make sure it is of type long, you must append an uppercase or lowercase letter L to the numeric value. So 100 as a long value is written as
100L.

Although it is perfectly legal to use it, a lowercase letter l is best avoided because it is easily confused with the digit 1. To declare and initialize the variable Big_Number, you could write this:
long Big_Number = 1287600L;

You write negative integer constants with a minus sign, for example:
int decrease = -4;
long below_sea_level = -100000L;

You specify integer constants to be of type long long by appending two Ls:
long long really_big_number = 123456789LL;

To specify a constant to be of an unsigned type, you append a U, as in these examples:
unsigned int count = 100U;
unsigned long value = 999999999UL;

To store integers with the largest magnitude, you could define a variable like this:
unsigned long long metersPerLightYear = 9460730472580800ULL;

The ULL specifies that the initial value is type unsigned long long.

SEMrush Software