Mega Code Archive

 
Categories / C++ Tutorial / Function
 

Demonstrate the pointer version of swap()

#include <iostream>  using namespace std;    void swap(int *x, int *y);    int main()  {    int i, j;      i = 10;    j = 20;      cout << "Initial values of i and j: ";    cout << i << ' ' << j << '\n';      swap(&j, &i); // call swap() with addresses of i and j      cout << "Swapped values of i and j: ";    cout << i << ' ' << j << '\n';      return 0;  }    void swap(int *x, int *y)  {    int temp;      temp = *x;   *x = *y;     *y = temp; } Initial values of i and j: 10 20 Swapped values of i and j: 20 10