A constant, like a variable, is a memory location where a value can be stored. Unlike variables, constants never change in value. You must initialize a constant when it is created. C++ has two types of constants: literal and symbolic.
Literals are data used for representing fixed values. They can be used directly in the code. For example:
'c' are literals. Why? You cannot assign different values to these terms.
Here’s a list of different literals in C++ programming.
- Integer Literal
- Floating-point Literals
- Escape Sequences
- String Literals
1. Integer Literal
An integer is a numeric literal(associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming:
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
Decimal: 0, -9, 22 etc Octal: 021, 077, 033 etc Hexadecimal: 0x7f, 0x2a, 0x521 etc
In C++ programming, octal starts with a
0, and hexadecimal starts with a
2. Floating Point Literal
A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For example:
3. Character Literal
A character literal is created by enclosing a single character inside single quotation marks. For example:
4. Escape Sequences
Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C++ programming. For example, newline (enter), tab, question mark, etc.
In order to use these characters, escape sequences are used.
|Single quotation mark|
|Double quotation mark|
5. String Literals
A string literal is a sequence of characters enclosed in double-quote marks. For example:
|null string constant|
|string constant of six white space|
|string constant having a single character|
|prints string with a newline|
The symbolic constant is a way of defining a variable constant whose value cannot be changed. It is done by using the keyword const.
const int c=5;
In C symbolic constant can be achieved by the use of #define.
When this statement is compiled, the pre-processor(#) will replace all the occurrence of PI with 3.142, which is then compiled into executable format.
A problem with this was the we cannot use any normal variable with same name PI throughout the program otherwise it will be replaced by its constant value. So this problem is solved in C++, by the use of const qualifier. The scoping of const values differs. A const in C++ is default to the internal linkage and therefore, it is local to the file where is is declared. While in C, constants values are global in nature. They are visible outside the file which they are declared. They can be made local by declaring them as static. To access the const value from another file we must explicitly define it as extern in C++.
extern const total=100;
Symbolic constant can also be defined using enumeration.
The enumerator n1 and n2 can be assigned constant value in following way:
const n1=1; const n2=70;