In C++, the “&” operator is known as the “address-of” operator. It is used to retrieve the memory address of a variable. This operator is particularly useful when dealing with pointers and passing variables by reference.
Here’s an example to illustrate the usage of the “&” operator:
#include <iostream>
using namespace std;
int main() {
int num = 10;
int* ptr = #
cout << "Value of num: " << num << endl;
cout << "Address of num: " << ptr << endl;
return 0;
}
In the code above, we declare an integer variable num
and assign it the value of 10. Then, we declare a pointer variable ptr
and assign it the memory address of num
. By using the “&” operator and prefixing it to the variable name (&num
), we obtain the memory address of num
and store it in ptr
.
When we print num
, it will display the actual value stored in the variable. However, when we print ptr
, it will display the memory address where the variable num
is stored.
The output of the above program would be:
Value of num: 10
Address of num: 0x7ffee8f585a8
In conclusion, the “&” operator in C++ allows us to obtain the memory address of a variable, enabling us to work with pointers and pass variables by reference.