CPP Tutorial



C++ CONSTANTS


🔸 Constants in C++

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.

Declaring Constants with 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.

Constants vs Variables

  • Variables can be changed after they are assigned.
  • Constants cannot be changed once assigned a value.

Using #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.

Example Program Using Constants

#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;
}
  

Summary

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.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review