- Constants are also the name given to the data values stored in memory like variable but the value of constant cannot be changed at the time of execution means when we don’t want to change the value of variable or want to same value at various place then we have to use constants. It is used to represent the fixed value which cannot be changed at runtime or cannot vary in the program after assigning the value to it at first time.
- There are several types of constant are present in C++. They are classified in the two groups as given below in the figure:
- Integer constant are sequence of number from digits 0 to 9 without any decimal point or fractional parts.
- Integer constants can be positive or negative.
- The number without any sign assumed to be positive number.
- Integer constants can be of minimum 2 bytes and maximum 4 bytes.
- Here are some examples of Integer constants:
45, -16, +56, 67 etc.
- String constants are sequence of characters enclosed in double quotes.
- Here are some examples of string constants:
“Ram”, “Good”,”1234″, “@@@@”
Declaration of Constants
- You have to declare the constant before using it into the program.
- Constant is declared using the keyword ‘const’.
- Here is the syntax for declaring constant in C++.
const data-type constant_name=data_value;
- Some examples of declaring constant in C++ are given here:
const int a=10; const float b=10.34; const char c=’a’;
- Here is an example of using constant in C++ program:
const int a=10;/*constant declaration*/
cout<<“nvalue of a is:”<<a;
- The output of the above program is as follows:
value of a is:10