How to Define Constants in C++?
Last Updated :
15 Jan, 2024
In C++, constants are the tokens that are used to represent those values that cannot be changed during the program execution. It is defined only once and remains the same throughout the execution of the program. C++ provides various different methods to define constants. In this article, we will discuss such methods to define constants and see how they are different form each other.
Different Ways to Define Constants in C++
In general, we can define constants using the const keyword but C++ also provides more methods to define constants. Some of the methods to define constants in C++ are:
- Using const Keyword
- Using Macro
- Using enum
- Using constexpr
Constants defined using each of these keywords have some similar and different properties. Let's discuss them one by one.
1. Constants Using const Keyword
This method is one of the most prominent and most basic methods of defining constants. Here, we use the keyword const as a prefix in the variable declaration.
Syntax
const variable_type variable_name = value;
We have to assign the value to the constant variable at the declaration as we cannot change its value after declaration.
Example
C++
// C++ program to demonstrate the declaration of constant
// using const keyword
#include <iostream>
using namespace std;
int main()
{
const float PI = 3.14;
cout << PI << endl;
// trying to change the value
PI = 111; // error will occur here
cout << PI << endl;
return 0;
}
Output
main.cpp: In function ‘int main()’:
main.cpp:13:8: error: assignment of read-only variable ‘PI’
13 | PI = 111; // error will occur here
| ~~~^~~~~
2. Defining Constant Using #define
Defining constants as a macro (using #define) is different from the method using const keyword as the constants are just a placeholder for the actual value. This alias is replaced by its value during the preprocessing.
Syntax
#define constantName value
Here, ConstantName is the name which is used as an alias to its value.
Example
The below example demonstrates the declaration of constant using #define.
C++
// C++ program to define constant using #define
#include <iostream>
using namespace std;
// defining constant
#define half 0.5
int main()
{
int base = 10;
int height = 10;
// Storing the value of area in a float data type
float area = half * base * height;
// calculating area of triangle
cout << "The area of right angle triangle is: " << area;
return 0;
}
OutputThe area of right angle triangle is: 50
3. Defining Constant Using enum
Enumeration (or enum) is a data type in which we assign some name to the integer values. We can use this property to create constant values. Enumerations are generally used where multiple constants are required and we can only use the integer values.
Syntax
enum enum_Name
{
constant1 = value;
constant2 = value;
}
Example
The below demonstrates the use of enum to create multi constants.
C++
// C++ program to demonstrate the use of enum to create
// multi constants
#include <iostream>
using namespace std;
// defining multiple constants using enum
enum No_Color { RED = 4, GREEN = 6, BLUE = 10 };
int main()
{
// printing values of all balls
cout << "The no. of Red Balls is " << RED << endl;
cout << "The no. of Green Balls is " << GREEN << endl;
cout << "The no. of Blue Balls is " << BLUE << endl;
return 0;
}
OutputThe no. of Red Balls is 4
The no. of Green Balls is 6
The no. of Blue Balls is 10
4. Defining Constant Using constexpr
In the C++11 and later versions, we can also use 'constexpr' keyword to declare constants. It its the modern and safe way to declare the constants in C++.This 'constexpr' keyword ensures that the value is processed at compile time instead of runtime to improve the execution efficiency.
Syntax
constexpr DataType constantName = value;
Example
The below example demonstrates the use of constexpr to define constant.
C++
// C++ program to demonstrate the use of constexpr to define
// constant.
#include <iostream>
using namespace std;
// Using constexpr to declare a constant variable
constexpr int Num = 5;
// Using constexpr to define a constant function
constexpr int factorial(int n)
{
return (n <= 1) ? 1 : n * factorial(n - 1);
}
int main()
{
// Using the constexpr constant variable
constexpr int res = factorial(Num);
cout << "Factorial of " << Num << " is: " << res
<< endl;
return 0;
}
OutputFactorial of 5 is: 120
Conclusion
In conclusion, constants in C++ programming are used to represent values that remain unchanged during program execution. The const keyword and other methods like #define, enum, and constexpr, allows us to declare and define constants as required. We can choose any of the above method based on our convenience and
Similar Reads
How to declare constant in react class ?
To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that constant is accessible class-wide. Constants can be declared in the following two ways: Create a getter method in the class for getting the constant wh
2 min read
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
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
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
VBA Constants in Excel
There can be situations when you want to declare a number in your program that you never want to be changed. In other situations, like, as if you have used a person's name many times in your program and you want to change that name, this assigned task could be hectic if you change the name of that p
6 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
Explain Constants in ES6
JavaScript is the world's most popular lightweight, interpreted compiled programming language. It is also known as a scripting language for web pages. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as
3 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
How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can't use the return keyword and it is implicitly invoked when the object is created. Constructor is also used to solve the problem of initialization. It is called after
2 min read
Importance of Constructors in C++
Constructors are special member functions in C++ that are invoked automatically when an object of a class is created. Their primary role is to initialize objects. In this article, we will learn all the factors that makes the constructor important in C++. Table of Content Initialization of ObjectsRes
8 min read