Constants/Literals in C++
Written by
Constants in C++ are the fixed values that can never change during the course of the program execution.
Any normal variable can be declared a constant, and once done the value of that particular variable cannot change in that program.
If one tries to change the value of a constant then an error occurs.
Constants are used generally for the values which are universally accepted.
For Example:
pi = 3.14 , g = 10 ms-2, etc.
Now, instead of writing these values again and again in a program one can simply define a constant with the desired value and use it everywhere without the possibility of an error.
How to declare a Constant?
Now, we have seen that what are constants, but how can we declare any variable a constant in C++. There are two ways in C++ to define constants:
1. Using #define preprocessor.
Syntax:
#define identifier value
For Example:
#include <iostream>
#define PI 3.14
int main()
{
int area, r = 10;
area = PI * r * r;
cout << "Area: " << area << endl;
return 0;
}
Output:
314
Here, #define PI 3.14
defines the value of PI as 3.14 using the #define preprocessor, now the value of variable PI will never change during the program execution.
2. Using const keyword:
The const
keyword can also be used to declare a constant in C++.
Syntax:
const data type variable_name = value;
For Example:
#include <iostream>
int main()
{
const float PI = 3.14;
int area, r = 10;
area = PI * r * r;
cout << "Area: " << area << endl;
return 0;
}
Output:
314
Here, const float PI=3.14;
defines the value of PI as 3.14 using the const keyword, now the value of variable PI will never change during the program execution and if one tries to do so, then an error occurs.
Literals:
Following are the literals in C++:
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
Example:
231
215u
0xFeeL
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
Example:
3.14159
314159E-5L
Character Literals
Character literals are enclosed in single quotes. Character literals include plain characters (e.g., ‘x’), an escape sequence (e.g., ‘\t’), or a universal character (e.g., ‘\u02C0’).
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords:
- A value of
true
representing true. - A value of
false
representing false.
String Literals
String literals are enclosed in double quotes.
Example
“C++ Programs”