C++ References C-PLUS-PLUS

C++ References  

C++ References

C++ References

A reference variable is a "reference" to an existing variable, and it is created with the & operator.

string food = "Pizza";  // food variable
string &meal = food;    // reference to food

Now, we can use either the variable name food or the reference name meal to refer to the food variable.

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";
  string &meal = food;

  cout << food << "\n";
  cout << meal << "\n";
  return 0;
}
 

Output:

Pizza
Pizza

Memory Address

The & operator was used to creating a reference variable. But it can also be used to get the memory address of a variable, which is the location of where the variable is stored on the computer. 

Note: The memory address is in the hexadecimal form (0x..)

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";

  cout << &food;
  return 0;
}
 

Output:

0x6dfed4

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries