C++ Constants
In C++ Language Constants is a fixed values that do not change during the execution of a program. These are also called Literals.
‘Pi’ is the best example for constants. Pi value is 3.414. which is fixed.
Syntax:
const data_type variable_name;
The type of constants that are listed below:
- Numeric Constants
- Character Constants
Numeric Constants:
In numeric constants, there are two types of other constants namely “Integer Constants and Real Constants”. The brief details about the two type of constants are given below.
1.Integer Constants:
Integer constants refer to a sequence of digits. There are three types of integers namely ‘decimals, octal and hexadecimal’.
- Decimal Integers consist of a set of digits i.e., 0 to 9, preceded by an optional – to the + sign.
- An Octal Integer constants consist of the combination of the digits from the set 0 through 7, with a leading 0.
- A hexadecimal integer consists of a sequence of digits preceded by 0X and 0x.
2.Real Constants:
Integer numbers are inadequate to represent the quantities that vary continuously. Such as prices, temperatures, distances, heights, and so on. Such type of numbers is called real numbers. There are decimal notation, exponential notation in Real Constants.
Character Constants:
In Character Constants there are two more constants are available namely “Single Character constants and String Constants.”
1.Single Character Constants
It defines a single character enclosed within a pair of single quote marks.
Ex: ‘4’, ‘Q’
2.String Constants
A sequence of character enclosed in " " quotes is called String Constant. The character may be in letters, numbers, special characters and blank spaces.
Ex: “Hello”, ”1976”’.
Defining C++ Constants
There are two different ways in C++ to define constants
- const keywords
- #define preprocessor
const keywords
In C++ programming the const keyword is used to define constants with a specific type.
Syntax
const data type variable = value;
Example
#include <iostream> using namespace std; int main(){ int r=10; float area; const float PI=3.14; area=PI*r*r; cout << "The value of PI is " << area << endl; return 0; }
The #define Preprocessor
To use #define preprocessor to define a constant in C++ programming.
Syntax
#define identifier value
Example
#include <iostream> #define Radius 20 using namespace std; int main(){ float area; const float PI=3.14; area=PI*Radius*Radius; cout <<"The value of PI is "<< area << endl; return 0; }
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.