In C++, a constant is a value that once defined, cannot be changed during the program execution. Constants are useful when you want to use fixed values that should not be accidentally modified.
const
The keyword const
is used before the data type to declare a constant:
const float PI = 3.14159; const int DAYS_IN_WEEK = 7;
After this declaration, you cannot change the value of PI
or DAYS_IN_WEEK
anywhere in the program.
#define
for Constants
Another way to define constants is using the #define
preprocessor directive:
#define MAX_SCORE 100 #define PI 3.14159
Note: #define
constants do not have a type, and are replaced by the preprocessor before compilation.
#include <iostream> #define MAX_USERS 50 using namespace std; int main() { const float PI = 3.14159; cout << "Value of PI: " << PI << endl; cout << "Maximum users allowed: " << MAX_USERS << endl; // PI = 3.14; // This will cause an error because PI is a constant return 0; }
Use const
to declare constants in C++ that hold fixed values throughout the program. Alternatively, #define
can be used for simple constants. Constants help prevent accidental changes to important values.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!