Constants are quantities whose values do not change during program execution. They may be numeric or character. There are three types of constants:
- Numeric constants
- Character constants
- String constants
- Boolean constants
Numeric constants consist of numbers. It can be further divided into two types.
- Integer constants:
Integers represent values that are counted, like the number of students in a class. An integer constant is a string of digits that does not include commas or a decimal point. Negative integer constants must be preceded by a negative sign. Some examples of valid integer constants are:
0, 453, -86, etc
- Floating point constants:
Floating point constants are numeric values with fraction or decimal point. Floating point constants represent values that are measured like the height of a person. Floating point constants are also called real constants.
54.6, 45.7, etc
A character constant is one of the symbols or characters in C++ character set. Any character written within single quotation mark is known as character constant. All alphabetic characters, digits and special symbols can be used as character constants. The maximum length of a character constant is 1 character.
Some of the examples of character constants are:
‘S’, ‘3’, ‘=’, etc
Character constants usually includes digits 0 to 9, uppercase letters A to Z, lowercase letters a to z, punctuation symbols such as semicolon, comma, period, the special symbols such as +, -, =, etc
The combination of \n is known as escape sequence. The backslash indicates (\) that a special effect is needed and the character following backslash specifies what to do. Similarly the \t escape sequence is used to tab over eight characters.
Using namespace std;
int main ()
The output of the above program will be:
A collection of characters written within double quotation mark is called string or string constant. It may consist of any alphabetic characters, digits and special symbols.
Some examples of string constants are as follows:
“City”, “country”, “123”, etc
Boolean constant can only store either true or false. There are two Boolean constants in C++
- True False
There are two ways to define constants in C++ programming language.
- Using #define preprocessor
- Using const keyword
#define identifier value
Identifier is the name of the constant and value is the value of the constant that will be fixed.
const data_type variable_name = value;