In C++ Constants can be considered as fixed values variables i.e. program can only access but cannot change those values. These values remain same throughout whole program execution. C++ Const reserve word and define pre-processor are the two ways to define constants in c++. There lies a difference between const and define pre-processor.
Defining a constant
A constant can be defined using
#define pre-processor directive;
#define constantname value;
E.g.
#include "stdafx.h"
#include "iostream"
using namespace std;
#define X 20; // a constant is defined with name X and value 20
void main()
{
cout << X;
getchar();
}
Output: –
Constants can also be created using const keyword as follows:
#include "stdafx.h" #include "iostream" using namespace std; void main() { const int X = 20; cout << X; getchar(); }
What is the difference between const and define?
Values defined using #define pre-processor directive can be changed by first un-defining those values and then set them again, while values set constant using const keyword cannot be redefined.
E.g.
Redefining #define
#include "stdafx.h"
#include "iostream"
using namespace std;
#define a 20;
void main()
{
cout << "Old value of a = " << a;
#undef a; // un-defining old value of a
#define a 300;
cout << "\nNew value of a = " << a;
getchar();
}
Redefining c++ const
#include "stdafx.h" #include "iostream" using namespace std; void main() { const int X = 20; cout << X; X = 30; cout << X; getchar(); }
Enumerated Constants: –
Enumerated constants create a set of constants using a single statement. They are created by using a keyword enum followed by a series of constants separated by a comma and are enclosed in curly brackets.
E.g.
enum names {Jan, Patrick, Michal};
initially, the values for these constants start from 0 and it increases value for next constant by 1 to value of the previous constant so on till the last constant.
#include "stdafx.h" #include "iostream" using namespace std; void main() { enum names { Jan, Patrick, Michal }; cout << "Value for JAN = " << Jan << endl; cout << "Value for Patrick = " << Patrick << endl; cout << "Value for Michal = " << Michal << endl; }
But we can also initialize these constants to our desired values.
E.g.
enum names {Jan = 10, Patrick = 20, Michal = 30};
#include "stdafx.h" #include "iostream" using namespace std; void main() { enum names { Jan = 10, Patrick = 20, Michal = 30}; cout << "Value for JAN = " << Jan << endl; coiuut<< "Value for Patrick = " << Patrick << endl; cout<< "Value for Michal = " << Michal << endl; }
Another variation in it is like:
#include "stdafx.h" #include "iostream" using namespace std; void main() { enum names{ Jan = 10, Patrick = 20, Michal}; cout << "Value for JAN = " << Jan << endl; cout << "Value for Patrick = " << Patrick << endl; cout << "Value for Michal = " << Michal << endl; }