Constants in C++ refer to variables with fixed values that cannot be changed. Once they are defined in the program, they remain constant throughout the execution of the program. They can be of any available data type in C++ such as int, char, string, etc.
Let's take a look at an example:
C++
#include <iostream>
using namespace std;
int main() {
// Declaring and defining a constant variable
const int c = 24;
cout << c;
return 0;
}
In the above code, the variable c is constant. It stored as read-only tokens in the code segment of the memory of the program.
Types of Constants in C++
In C++, constants can be classified on the basis of the way using which they are created. In C++, constants can be defined using three ways:
- Using const Keyword
- Using constexpr Keyword
- Using #define Preprocessor
Using const Keyword
Defining constants using const keyword is one of the older methods that C++ inherited from C language. In this method, we add the const keyword in the variable definition as shown below:
Syntax
const DATATYPE variable_name = value;
We have to initialize the constant variable at the time of declaration as we cannot modify the value of it later in the program.
Example
C++
#include <iostream>
using namespace std;
int main() {
int var = 10;
// Declaring a constant variable
const int c = 24;
// Trying to change the value constant c
c = 0;
cout << c;
return 0;
}
Output
./Solution.cpp: In function 'int main()':
./Solution.cpp:19:10: error: assignment of read-only variable 'cons'
cons = 0;
Using constexpr Keyword
The constexpr keyword is similar to const keyword and is also used to declare constants in C++. But the major difference is that the constexpr constants are initialized at compiler time, which is why their value must be known at the compile time. On the other hand, const keyword constants can be initialized at runtime and compile time.
Syntax
constexpr DATATYPE variable_name = value ;
Example
C++
#include <iostream>
using namespace std;
int main() {
// Defining constant
int constexpr hoursIn_day = 24;
// Printing value
cout << hoursIn_day;
return 0;
}
The above snippet uses the constexpr keywords to define constant the number of hours in a day (hoursIn_day)
Using #define Preprocessor
We can also define constants using the #define. Constants created using the #define preprocessor are called "macro constants". Unlike the other methods, constants defined using this method simply work as an alias for their value which is substituted during preprocessing.
It is the less preferable way to define a constant in C++ due to the lack of type safety.
Syntax
#define MACRO_NAME replacement_value
Example
C++
#include <iostream>
using namespace std;
// Using #define to create a macro
#define Side 5
int main()
{
// Using constant
double area = Side * Side;
cout << area;
return 0;
}
Explanation: We have defined the macro constant Side with the value of 5. We then used it to find the area of the square. The macro constant Side is global meaning it is not restricted to a single function. Also, note that we cannot get user input for the macro constant.
Important Points about Constants
The following are some major properties of C++ constants discussed in the article:
- Constants are the variables with fixed values.
- We have to initialize the constants at the time of declaration, and we cannot change this value later in the program.
- const and constexpr can be used to define a constant.
- #define is also used to define a macro constant.
Similar Reads
errno constant in C++
errno is a preprocessor macro used for error indication. The value of errno is set to zero at program startup, and any function of the standard C++ library are allowed to write positive integers to errno whether or not an error occurred.Once the value of errno is changed from zero to non zero then n
4 min read
Constants in LISP
In LISP all constants are global variables. Values of constant never change throughout the execution of the program. Defining constant in LISP: New global constants are defined using the DEFCONSTANT construct Syntax: (defconstant name initial-value-form "documentation-string") Example: Let's create
2 min read
SciPy - Constants
Scipy stands for Scientific Python and in any Scientific/Mathematical calculation, we often need universal constants to carry out tasks, one famous example is calculating the Area of a circle = 'pi*r*r' where PI = 3.14... or a more complicated one like finding forcegravity = G*M*m â (distance)2 wher
3 min read
Constants in Objective-C
Constants in Objective-C are values that cannot be modified once they are set. They are used to store a variety of data types, including numbers, strings, and booleans. Constants are a fundamental feature of the Objective-C programming language and are widely used in the development of applications
4 min read
Constant Folding
As we all know humans understand only programming languages like C, C++, Python, Java, etc. whereas a computer can only understand bytecodes or machine languages. So compiler acts as a converter. Its aim is to convert the high-level language to machine-level language. However, during conversion, som
3 min read
Constant in Maths
In mathematics, a constant is a value that does not change. It is fixed and remains the same throughout a given problem or equation. Constants can appear in various forms, such as specific numbers, variables with known values, or symbols representing unchanging values. Some examples for constants ar
4 min read
Dart - Constants
In Dart language, Constants are objects whose values cannot be changed during the execution of the program. Hence, they are a type of immutable object. A constant cannot be reassigned any value if a value has been assigned to it earlier. If we try to reassign any value to a constant, Dart throws an
2 min read
Rust - Constants
Constants are the value that can not be changed after assigning them. If we created a constant, then there is no way of changing its value. The keyword for declaring constant is const. In Rust, constants must be explicitly typed. The below syntax is used to initialize a constant value: Syntax : cons
1 min read
Constants in Physics
Constants in Physics are fundamental values that remain unchanged across different contexts and experiments. These constants are universal in nature and are independent of the unit system used. They are essential for verifying the accuracy of theories and enabling practical applications based on tho
7 min read
Built-in Constants in R
R is a popular programming language and environment for statistical computing and graphics, providing a variety of built-in constants that are useful for different types of data analysis and scientific computations. Understanding these constants is essential for efficient coding and accurate results
3 min read