int pass by reference c++ code example

Example 1: passing reference in c++

// C++ program to demonstrate differences between pointer 
// and reference. 
#include <iostream> 
using namespace std; 
  
struct demo 
{ 
    int a; 
}; 
  
int main() 
{ 
    int x = 5; 
    int y = 6; 
    demo d; 
      
    int *p; 
    p =  &x; 
    p = &y;                     // 1. Pointer reintialization allowed 
    int &r = x; 
    // &r = y;                  // 1. Compile Error 
    r = y;                      // 1. x value becomes 6 
      
    p = NULL;            
    // &r = NULL;               // 2. Compile Error 
      
    p++;                        // 3. Points to next memory location 
    r++;                        // 3. x values becomes 7 
      
    cout << &p << " " << &x << endl;    // 4. Different address 
    cout << &r << " " << &x << endl;    // 4. Same address 
      
    demo *q = &d; 
    demo &qq = d; 
      
    q->a = 8; 
    // q.a = 8;                 // 5. Compile Error  
    qq.a = 8; 
    // qq->a = 8;               // 5. Compile Error 
      
    cout << p << endl;        // 6. Prints the address 
    cout << r << endl;        // 6. Print the value of x     
  
    return 0; 
}

Example 2: calling by reference and pointers c++

#include <iostream>
using namespace std;

// Function prototype
void swap(int&, int&);

int main()
{
    int a = 1, b = 2;
    cout << "Before swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    swap(a, b);

    cout << "\nAfter swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}

void swap(int& n1, int& n2) {
    int temp;
    temp = n1;
    n1 = n2;
    n2 = temp;
}

Tags:

Misc Example