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.
A constant is an explicit number or character (such as 1, 0.5, or ‘c’) that doesn’t change.
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:
- MAX_SPEED is a constant that holds the value 180.
- The const keyword ensures that the value of MAX_SPEED cannot be changed after initialization.
Output:
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:
- define MAX_SPEED 180 creates a constant MAX_SPEED with the value 180.
- define is a preprocessor directive and is replaced at compile time, so it works a bit differently than const.
Output:
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.
C++ Constant – Interview Questions
Q 1: What is a constant?
Q 2: How do you define a constant?
Q 3: Can constants be modified?
Q 4: Why use constants?
Q 5: Example of constant declaration?
C++ Constant – Objective Questions (MCQs)
Q1. Which keyword is used to define a constant variable in C++?
Q2. What will happen if you try to change the value of a variable declared as const in C++?
Q3. Which of the following correctly defines a constant integer in C++?
Q4. Which preprocessor directive is used to define a symbolic constant in C++?
Q5. What is the output of the following code?
const int x = 5;
cout << x;