In C++ Constants is core part and important in C++ programming language. As the name suggests Constants are fixed value type that means the value of constant never going to change during the execution of the program.
There are key important things about Constants in C++
- Constants and literal both are same. Sometimes constant is called literal
- Any data type can be defined as constant or literal.
- It is considered a best practice to define constants using only upper-case names.
Declaration of Constants
There are two ways to define a constant
- Const keyword
- #define preprocessor
Syntax of constant
const data_type constant_name;
The following example Constant in detail −
using namespace std;
#define length 5
#define bredth 6
//Constants are expressions with a fixed value.
const int SIDE = 10;
square = SIDE*SIDE;
rectangle = length*bredth;
cout<<"The square area is "<< square;
cout<<"The rectangle area is "<< rectangle;
The area is 100
Constants can be of following types.
- integer constant.
- floating constant.
- character constant.
- string constant.
Following table shows the constants and its data types with Example
|constant type||data type(Example)|
|integer constant||int (53, 762, -478 etc ) unsigned int (5000u, 1000U etc) long |
int, long long int (483,647 2,147,483,680)
|floating constant||float (10.456789) double (600.123456789)|
|character constant||char (Example: ‘A’, ‘B’, ‘C’)|
|string literal||char (Example: “ABCD”, “Hai”)|