Ad Code

Responsive Advertisement

C++ references - Learn CPP

C++ references - Learn CPPThe concept of references is used within a group of programming languages, including the C++ programming language, and references are addresses that are given to any element in the code, such as variables, arrays, and objects, which are defined in memory when the program is run. It is allocated a special space in memory and is used in a (Hexadecimal) manner.

Access to the items in memory is very important, as it makes the programmer able to reduce the space that the program needs from memory, and it may also make the size of the code smaller, as the programmer can access the items in it directly, and this is necessary for large software projects, and the possibility of Accessing the elements in memory is the most important characteristic of the C++ programming language from other programming languages ​​in which this is not possible, such as the Java programming language and the Python programming language. To access the addresses of the elements in memory, the (&) operator called (Address Operator) is used.


C++ references - Learn CPP



Printing addresses of in-memory objects in C++


The address of any variable defined in memory is printed with an (&) before its name as we will see in the following example:


#include <iostream>

using namespace std;

int main () {

int y = 10;

cout << "Address of y in memory: " << &y;

return 0;

}


In the previous example, a variable named (y) was defined and the address of the space allocated to the variable was printed with an (&).


How to bind two variables to the same address in memory in C++


It is possible for the programmer in the C++ programming language to define a variable and then access it directly with a different name. This is done by defining another variable and making it point to its address in memory, as in the following example:


#include <iostream>
using namespace std;

int main () {

int x =7;

int &y= x;

cout << "x = " << x << endl;

cout << "y = " << y;

return 0;

}

In the previous example, a variable named (x) was defined, and then a variable named (y) was defined pointing to the same address of the variable (x), and in this case, two variables were linked to the same address in memory.