What are Constants in C++?

, ,

What are Constants?

Constants are like a variable, except that their value never changes during the program execution once defined. Constants refer to as fixed values, unlike variables whose value can be altered, constants – as the name implies does not change, they remain constant. Constant must have to be initialized at the time of creating it and new values cannot be assigned later to it.

Constant Definition in C++

There are two other different ways to define constants in C++. These are:

  • By using const keyword
  • By using #define preprocessor

Constant Definition by Using const Keyword

const type constant_name;
#include <iostream>using namespace std;int main(){  const int SIDE = 50;  int area;  area = SIDE*SIDE;  cout<<"The area of the square with side: " << SIDE <<" is: " << area << endl;  system("PAUSE");  return 0;}


It is also possible to put const either before or after the type.

int const SIDE = 50;


const int SIDE = 50;

Constant Definition by Using #define preprocessor

#define constant_name;
#include <iostream>using namespace std;#define VAL1 20   #define VAL2  6#define Newline '\n'int main(){   int tot;    tot = VAL1 * VAL2;   cout << tot;   cout << Newline;}

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *