Constants in CplusPlus C++
Constant ( Constant ) Anything that is defined in such a way that its value cannot be changed.
To define a variable or object as a constant we use the word const
and then we are unable to change its value.
The word const
can be used with either:
Variables (Variables) .
Indications (Pointers) .
Parameters of functions (Functions Parameters).
Class characteristics (Class Member Variables).
class functions (Class Member Functions).
Objects (Objects).
How to define a constant variable in C++
If you define a constant variable, you cannot change its value later and you must give it a value directly when defining it.
The value placed inside a variable can be obtained as normal as the value placed inside a normal variable, but it can only be changed.
In the following example, we have defined a static variable named x
its value 10
and then we tried to re-change its value.
First example: Defining a variable as a constant in C++
#include <iostream> using namespace std; int main() { // قيمته تساوي 10 x هنا قمنا بتعريف متغير ثابت إسمه const int x = 10; // x هنا قمنا بطباعة قيمة المتغير cout << "x = " << x; return 0; }
• We will get the following result when running.
x = 10
In the following example, we have defined a static variable named x
its value 10
and then we tried to re-change its value.
The second example is defining a variable as a constant in C++
#include <iostream> using namespace std; int main() { const int x = 10; // its value is 10 x here we have defined a constant variable named x = 5; // which will cause an error x here we tried to change the value of the variable return 0; }
• The following error will appear when running, which means that the value in the variable cannot be changed x
.
How to define a pointer as a constant in C++
The normal pointer can at any time be made to point to anything in memory, as we have seen.
Defining the pointer itself as a constant makes the pointer specific to the thing it was made to point to when it was defined while not being able to make it point to something else later.
In the following example, we have defined a variable whose name is x
its value 5
and a variable whose name is y
its value 7
.
Then we created a fixed pointer whose name ptr
indicates the value of the variable x
and then we tried to make it point to the value of the variable y
, which will cause a problem when running.
Example of defining a pointer as a constant in Cplus
#include <iostream> using namespace std; int main() { // y and x here we have defined the two variables int x = 5; int y = 7; // in memory x and make it point to the address of the ptr variable here we have defined the static pointer int* const ptr = &x; // in memory which will cause an error when running y points to the address of the ptr variable here we tried to make the pointer ptr = &y; return 0; }
• The following error will appear when running, which means that the value indicated by the indicator cannot be changed ptr
.
How to define a pointer to a constant in C++
If you have a static variable, you can create a pointer to it, but then you have to create the pointer as a constant as well, which makes you unable to make it point to something else later.
In the following example, we have defined a constant variable whose name is x
its value 10
and a constant pointer whose name ptr
indicates its value.
Finally, we display the value that the pointer points to ptr
in memory.
Example of defining a pointer for a constant in CPLUS
#include <iostream> using namespace std; int main() { // its value is 10 x here we have defined a constant variable named const int x = 10; // in memory x and make it point to the address of the static variable ptr Here we have defined the static pointer const int* ptr = &x; // ptr Here we have printed the value of the static variable to which the static pointer is pointing cout << "*ptr = " << *ptr; return 0; }
• We will get the following result when running.
*ptr = 10
In the previous example, the fixed pointer ptr
that we defined in line 11 we can define it like this and get the same result.
const int* const ptr = &x;
This is also a different way to define it.
int const* ptr = &x;
How to define the parameter of a function as a constant in C++
In the event that you intend to pass the value of a constant variable to a function and you want the value being passed to be treated as a constant as well, you must know the type of parameter in the function as a constant.
In the following example, we have defined a function whose name addOne
when called, we pass a number to it, and it will add 1
to it and return its value.
The first example in defining the parameters of a function as a constant in CPLUS
#include <iostream> using namespace std; // When it is called, we pass it any number and it returns its value plus 1 addOne. Here we have defined a function named int addOne(int n) { // n Here we have added 1 to the value in the variable n++; // n here we have returned the value of the variable return n; } // main() Here we have defined the function int main() { // its value is 5 x here we have defined a constant variable named const double x = 5; // her and print the output that x will return and pass the value of addOne() here we have passed a value with the function call cout << "5 + 1 = " << addOne(x); return 0; }
• We will get the following result when running.
5 + 1 = 6
In the following example, we repeated the previous example, but this time we made the value passed to the function to be considered a constant value, which will cause an error when running.
Note: We have marked the line on which we made the modification in yellow.
second example
#include <iostream> using namespace std; // as a constant n here we have defined the parameter int addOne(const int n) { // n The following line will cause an error when running because it does not allow the value of the constant to be changed n++; return n; } int main() { const double x = 5; cout << "5 + 1 = " << addOne(x); return 0; }
• The following error will appear when running, which means that the value of the constant cannot be changed n
.
In the following example, we have defined a constant variable that represents the price of a product whose name price
and value are 50
.
Then we defined a function whose name finalPrice()
when called, we pass the constant to it, and it price
returns to us the price of the product, deducted from it 20 %.
first example
#include <iostream> using namespace std; // also double and when called we must pass it the name of a constant variable of type double returns the value of its type finalPrice Here we have defined a function with its name double finalPrice(const double n) { // Here we wrote an equation for the value that the function will return, which will eventually give the value of the number we pass to it - 20% of it return n - (n * 0.2); } // main() Here we have defined the function int main() { // Represents the price of a product and its value is 50 price. Here we have defined a variable named const double price = 50; // and print the final result that will be returned as the final price after deduction finalPrice() to the price function here we pass the value of the variable cout << "Price after 20% sold = " << finalPrice(price) << "$"; return 0; }
• We will get the following result when running.
Price after 20% sold = 40$
We will repeat the same example as before, but this time we will store the value that we pass to the function in a variable and then deal with the new variable that was passed to the function.
Note: If you intend to perform multiple operations on the value being passed to a function, this approach is better and easier for you.
second example
#include <iostream> using namespace std; double finalPrice(const double n) { // thePrice Here we store the value of the constant in a variable named int thePrice = n; // by 20% and the final result is also stored in thePrice here we have done a discount on the value in the variable thePrice -= (thePrice * 0.2); // thePrice Here we have returned the value of the variable return thePrice; } int main() { const double price = 50; cout << "Price after 20% sold = " << finalPrice(price) << "$"; return 0; }
• We will get the following result when running.
Price after 20% sold = 40$
Define constant properties in the class in C++
If you want to define static properties in the class, meaning that the values we give them cannot be changed later, you must pass values for each static property you defined in the object at the moment of creating the object and do that through the object constructor as we will see now.
In the following example, we have defined a class whose name Player
contains a constant variable named name
in addition to a constructor that allows us to pass a value to the constant name
.
An example of defining the properties of a class constant in C+
#include <iostream> using namespace std; // Player Here we have created a class called class Player { public: // name Here we have defined a constant (property) variable named const string name; // Here we have defined a constructor that should be given a value when called // name and then put in the property n the value we pass to it is temporarily stored in the variable Player(string n): name(n) { } }; // main() Here we have defined the function int main() { // name which will be set as the value of the property n and pass a value to it in the place of the parameter player named Player Here we created an object from the class Player player("Mhamad"); // player owned by the name object Here we have shown the property value cout << "Player Name = " << player.name; return 0; }
• We will get the following result when running.
Player Name = Mahamad
In the previous example, if you wanted to name the parameter in the constructor as the name
name of the property and get the same result, the constructor would look like this.
const string name; Player(string name):name(name) { }
Information: If you want to pass a value to more than one constant in the constructor, you must put commas between each two values as follows.
const string name; const int age; Player(string n, int a): name(n), age(a) { }
Define the object as a constant in C++
If you want to create a static object meaning that the value of any property in it cannot be changed, you can create the object as a static object.
When creating a static object from a class, you cannot call any function in the class that deals with a property in it unless you make the function static from the ground up.
In the following example, we have defined a class whose name Player
contains two variables named name
and age
as normal properties.
We have also defined a constructor that allows us to pass values to properties name
and age
a static function that can be used to display their values in order.
Example of defining an object as a constant in C++
#include <iostream> using namespace std; // Player Here we have created a class called class Player { public: // age and name here we have defined properties string name; int age; // Here we have defined a constructor that allows us to pass values to properties when defining an object // Because we must pass raw values to all properties of the object if we are going to create it as a static object Player(string name, int age) { this->name = name; this->age = age; } // as a static function so that we can call it if we create a static object from the printInfo() class here we have defined the function void printInfo() const { cout << "Name = " << this->name << endl; cout << "Age = " << this->age << endl; } }; // main() Here we have defined the function int main() { // Passing raw values of its properties through the constructor player named Player Here we create a static object of the class const Player player("Mhamad", 26); // In order to display the values of the properties in it in order player here we called the function from the static object player.printInfo(); return 0; }
• We will get the following result when running.
Name = Mahamad Age = 26
word mutable
in C++
In the event that you intend to create a static object from the class, but you want to make some of its properties immutable, meaning that their values can be changed later after creating the object, you must know the property that you want to make its value immutable mutable
so that the compiler understands that you want it.
In the following example, we have defined a class whose name Player
contains three variables named name
and age
and job
as properties in the class.
We made the property job
its type mutable
so that we can change its value whenever we want from the object we create from the class, even if we create it as a static object.
We have also defined a constructor that allows us to pass values to properties name
and age
a static function that can be used to display the values of all properties in order.
An example of the use of the word mutable in CPLUS
#include <iostream> using namespace std; // Player Here we have created a class called class Player { public: // mutable is of type job and note that the property ,job and age ,name here we have defined properties string name; int age; mutable string job; // When creating an object because it must age and name here we have defined a constructor that allows us to pass values for the two properties // mutable to pass raw values to each property of the object in case we are going to create it as a static object as long as its type is not Player(string name, int age) { this->name = name; this->age = age; } // as a static function so that we can call it if we create a static object from the printInfo() class here we have defined the function void printInfo() const { cout << "Name = " << this->name << endl; cout << "Age = " << this->age << endl; cout << "Job = " << this->job << endl; } }; // main() Here we have defined the function int main() { // Passing raw values of its static properties through the constructor player named Player Here we create a static object from the class const Player player("Mhamad", 26); // As we said before, mutable and we can do this because its type is player that the job object has here we set a value for the property player.job = "Programmer"; // In order to display the values of the properties in it in order player here we called the function from the static object player.printInfo(); return 0; }
• We will get the following result when running.
Name = Mahamad Age = 26 Job = Programmer
word # define
in C++
The word #define
can be used to define a variable whose value is constant, like the word const
, but in a different way.
In the following example, we have defined a constant variable whose name MAX_VALUE
is . 1000
.
An example of the use of the word define in C++
#include <iostream> using namespace std; #define MAX_VALUE 1000 int main() { // MAX_VALUE whose value is equal to the value of the constant x here we have defined a variable named int x = MAX_VALUE; // x here we have printed the value of the variable cout << "x = " << x; return 0; }
• We will get the following result when running.
x = 1000
Attention
The word #define
may cause unexpected problems in the program because the type of value that is placed in it is not specified, so it is better to define the static variable always by the word const
rather than the word #define
.