reference is pointer c++ code example

Example 1: pointer in c++

// Variable is used to store value
int a = 5;
cout << a; //output is 5

// Pointer is used to store address of variable
int a = 5;
int *ab;
ab = &a; //& is used get address of the variable
cout << ab; // Output is address of variable

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:

Java Example