Constants in C++
As the name suggests, named constants are variables or values in the C++ programming language that, once defined, cannot be changed. They are fixed values within the program. Any kind of constant can be used, including integers, floats, octal, hexadecimal, and character constants. Each constant has a specific range. Integers too large to fit in an int are taken with the same length. Now there are different ranges from unsigned bits to signed bits.
For Example:
const int num= 25 ; // num is always 15
num = 25; // error: assigning read-only variable 'num'
If it has a low value, it should always be declared as a constant.
const int mintperhour = 60 ;
constant float PI = 3.14 ;
You will Learn following Concepts
- This article explains what C++ constants are and how to define them in C++ with examples .
- The literals and their types are explained in detail with examples.
C/C++ programs can define constants in two ways:
- Use the #define preprocessor directive.
- Use the const keyword. For example, "const int = 5;" is a constant expression and the value 5 is called a constant integer literal.
Let's take a closer look at the above two methods.
Using the #define preprocessor directive:
This directive is used to declare an alias for an existing variable or any value. Can be used for confirmation
This preprocessor directive provides an alias or reference name for a variable or value. Used to define constants in C++ by giving an alias to the value. This method defines a constant globally.
Syntax:
#define ConstantName Value
ConstantName:
An identifier for referencing the value in code. Value: The value for which the reference is created.
Using the const keyword:
Characterizing a constant with the const keyword is basically as easy as characterizing a variable, but in practice the definition must be preceded by the const keyword. I have.
Code in C++
cout << "integer constant: " << intNmb << endl ;
integer constant: 101
float constant: 31.14
character constant: M
string constant: ABZ
0 Comments