At one time, all of us were tired of maths, but it has some fundamental concepts still in use, and everyone might know about it: Constants. Like in our life, we have some constants, i.e., whose place no one can take or which can not be changed, and in mathematical terms, its value can not change, same as we have in our very own C++ language. So, let us know more about the constants.
What are Constants in C++?
Constants are a variable whose values cannot be altered or changed. They are also known as literals because we can write them in the text without escape sequences. Using a constant value helps when you need to specify a fixed value throughout your program, which does not change. A variable value can change anytime and may put the program in the wrong state.
How to Declare a Constant in C++?
Now to declare a constant in C++, we got two ways, i.e.,
- Using #Define pre processer
- Using the keyword Const
1. Using #Define pre processer
Syntax
#define identifierName value
Example
// Using #define
#include <iostream>
using namespace std;
#define choco 5
#define took 2
int main()
{
int remaining;
remaining = choco - took;
cout << remaining << "\n";
cout << choco << "\n";
return 0;
}
OUTPUT
3
5
The above program will return the value of choco as 5 and the remaining as 3.
It will show an error if we try and change the value of choco by inserting int choco=4; in the main class because we have declared it as constant using the 1st approach, i.e., using #define pre processor.
2. Using the keyword Const
syntax
const return_type variable_name = value;
Example
// Using const
#include <iostream>
using namespace std;
int main()
{
const int choco = 5;
const int took = 2;
int remaining;
remaining = choco - took;
cout << remaining << "\n";
cout << choco << "\n";
return 0;
}
OUTPUT
3
5
We have taken the same example, but using the 2nd approach, i.e., by using the const keyword for constant here, which is used more by the programmers while creating more substantial programs, which helps control the scope of the variable declared as constant.
CONCLUSION
In this blog, we’ve learned about another crucial topic moving towards the step of learning C++ programming, i.e., Constants, what they are, how to use them, and how they make our life as a programmer much more manageable. We’ve also learned about constants and how we can create one when we do not wish to change the values assigned to certain constants.
As you all know, GeekonPeak has just begun and is looking for some loyal supporters so we, the new-gen geeky friends, can grow and create more comprehensive and easy-to-grasp courses for you (for free). Follow us on Facebook, Instagram & Twitter as well. Also, don’t miss our newsletter subscription. We provide exclusive blogs, tips, tricks, and advice to program efficiently and market smartly. We also promote some of our partners with excellent experiences to share with you. Until next time 🙂