Website For Developers

Constants in C++

• Constant means something that cannot be changed like unchanging factors, unchanging state of affairs, unchanging conditions.
• Constants in C++ means something that cannot be changed.
• There are two types of Constants in C++:

Literal Constant in C++

Literal constant in C++ is a type of value which is used directly in a program where it is needed.
For example:

Int value= 55;

In the statement given above value is integer and 55 is a constant value which is called literal constant.

There are Four different types of literal constant in C++:
1. Integer Constant
2. Floating point constant
3. Character constant
4. String Constant

1. Integer Constant
    • Integer constants are integer type constant which has numeric values.
    • Decimal and fractions values are not counted in integer constant values.
    • Both positive and negative type values in integer constant can used.
    • For Example: 55 88 -99 -12
    • If we want to use long integer values we need to put “L” in the end of the numeric values.
    • For Example: 54000L 73000L

2. Floating Point Constant
    • Floating point constant is also like integer constant type values.
    • But unlike integer constant we can use decimal and fraction values in floating point constant.
    • f or F is used in the end of values to make them floating point values.
    • For example: 33.42F -1.92F
    • For double values there is no need to add anything in the end.
    • For Example: 33.42 89.56
    • But for long double value L is added in the end of the value.
    • For Example: 43000.99L

3. Character Constant
    • Any character type value which is written in a single quote is called Character Constant.
    • All alphabetic character, Symbols and digits are used in character constant type.
    • For Example: 'A' 'B' '=' '+' '$'

4. String Constant
    • A set of characters which is written in double quotation or double commas is called String Constant.
    • For Example: "Programming Hub"

Symbolic Constant in C++

A symbolic constant is used to assign a name to the value that cannot be changed afterwards.
Once a constant initialized its value is same throughout the program.
Symbolic constant are mostly used to represent the value which is mostly used in the program.

#define PI 3.141593

There are two ways to describe symbolic constant in C++:
1. Const qualifier
2. Define qualifier

1. const qualifier
    • Const qualifier is mostly used to describe a constant by name.
    • It must be initialize by some value.
    • For example: const int x = 3;

2. define directive
    • Define directive starts with the symbol # and it is not terminated by the semicolon.
    • It is also used to describe the constant.
    • But it does not specify the data type of constant like const qualifier.
    • For example: #define PI 3.141593;