WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Basic · question 5 of 100

What is the purpose of the ’const’ keyword in C++?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

The ’const’ keyword in C++ is used to indicate that a variable, function parameter, or member function does not change its value or state during the execution of the program. It is a way to enforce immutability and to prevent accidental modifications of data that should not be changed.

There are two main uses of the ’const’ keyword in C++:

To declare a constant variable:

You can use the ’const’ keyword to declare a variable as constant, which means that its value cannot be changed after initialization. This is useful when you want to define a value that should remain fixed throughout the program’s execution. For example:

    const int myConstant = 42;

This declares a constant integer variable called myConstant with an initial value of 42. Any attempt to change the value of myConstant will result in a compilation error.

To declare a function parameter or member function as constant:

You can use the ’const’ keyword to declare a function parameter or member function as constant, which means that it does not modify the state of the object it operates on. This is useful when you want to ensure that a function does not have side effects or modify the data it operates on. For example:

    class MyClass {
        public:
        int getValue() const {
            return myValue;
        }
        
        private:
        int myValue;
    };

This declares a member function called getValue() that returns the value of the private member variable myValue. The ’const’ keyword at the end of the function declaration indicates that the function does not modify the state of the object it operates on. This ensures that the function can be safely called on a constant object without the risk of modifying its state.

In addition, the ’const’ keyword can also be used to declare pointers to constant data or constant pointers to data. For example:

    const int *myPointer; // pointer to constant integer data
    int *const myConstantPointer; // constant pointer to integer data

In summary, the ’const’ keyword in C++ is used to indicate that a variable, function parameter, or member function does not change its value or state during the execution of the program. It is a way to enforce immutability and to prevent accidental modifications of data that should not be changed.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics