reference variable c++ code example

Example 1: reference function in c++

// function definition to swap the values.
void swap(int &x, int &y) {
   int temp;
   temp = x; /* save the value at address x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
  
   return;
}

Example 2: c++ declare variable

std::string str = "text";	// stores a string
int    foo = 3;				// stores any integer
float  bar = 3.14;			// stores 32 bit number
double baz = 3.14159265;	// stores 64 bit number

Example 3: reference variablesr in c++

#include <iostream>
 
using namespace std;
 
int main () {
   // declare simple variables
   int    i;
   double d;
 
   // declare reference variables
   int&    r = i;
   double& s = d;
   
   i = 5;
   cout << "Value of i : " << i << endl;
   cout << "Value of i reference : " << r  << endl;
 
   d = 11.7;
   cout << "Value of d : " << d << endl;
   cout << "Value of d reference : " << s  << endl;
   
   return 0;
}

Example 4: reference variablesr in c++

Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

Tags:

Cpp Example