C++ Constants/ Literals: In C++ Constants/ Literals are nothing but they refer to fixed values. Their values cannot be changed once they are assigned. Constants can be of any of the basic data types. And these can be divided into integer numerals, floating point numerals, characters, boolean values, and strings.
C++ Constants/ Literals
- Integer Literals
- Floating Point Literals
- Boolean Literals
- Character Literals
Integer Literals
An integer literal can be octal, decimal (or) hexadecimal constant. And the integer literal can also have a suffix that is a combination of U and L for unsigned and long. The suffix value can be in any order.
Examples:
85 //decimal 0213//octal 0x4b//hexadecimal 30 //int 30u //unsigned int 30l //long 30ul //unsigned long
Floating Point Literals
A floating point literal consists of an integer part, decimal point, fractional part, and an exponent part. We can also represent them in decimal form (or) an exponential form.
If you are representing using the decimal form we must include the decimal point, exponent or both. And in case if you are representing an exponential form we should include the integer part (or) fractional part.
Example:
3.14159//Legal 314159E-5L//Legal 510E//Illegal: incomplete exponent 210f//Illegal: no decimal or exponent .e55 /Illegal: missing integer or fraction
Boolean Literals
There two types of boolean literals present in C++. They are true and false. In this, we should not consider that the value of true is 1 and the value of false is 0.
Character Literals
These are enclosed in single quotes. And the literal letters begin with L i.e. upper case only and wide character literal i.e L’x’ these should be stored in a simple variable of char type.
The character literal can be a plain character(i.e. ‘y’) (or) an escape sequence (i.e. \’t’) or an universal character. (i.e.’\u02C0′).
Constant Definition in C++
In C++ they are different ways to define a constant. They are as follows:
- Using const keyword
- Using #define preprocessors
Constant Definition by Using const keyword
Syntax: const type constant_name;
Example:
#include <iostream> using namespace std; int main() { const int SIDE = 50; int area; area = SIDE*SIDE; cout<<"The area of the square with side: " << SIDE <<" is: " << area << endl; system("PAUSE"); return 0; }
Output:
The area of the square with side: 50 is: 2500
Press any key to continue…
If you want we can place const keyword before (or) after
int const SIDE = 50;
(or)
const int SIDE = 50;
Constant Definition by using #define preprocessor
Syntax: #define constant_name;
Example:
#include <iostream> using namespace std; #define VAL1 10 #define VAL2 6 #define Newline '\n' int main() { int tot; tot = VAL1 * VAL2; cout << tot; cout << Newline; }
Output:
60