In: Computer Science
Please write the following swap functions and print code in main to show that the functions have adequately . Your code should, in main(), print the values prior to being sent to the swap function. In the swap function, the values should be swapped and then in main(), please print the newly swapped values.
1) swap integer values using reference parameters
2) swap integer values using pointer parameters
3) swap pointers to integers - you need to print the addresses, not the integers.
Following is the code in swap.cpp :
#include <iostream>
using namespace std;
void swap_by_reference(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void swap_by_pointers(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void swap_pointers(int **a, int **b)
{
int *temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a, b;
/*
* Reinitialize a, b.
*/
a = 42;
b = 786;
cout << endl << endl;
cout << "Before SWAP-BY-REFERENCE, a = [" << a << "], b = [" << b << "]" << endl;
swap_by_reference(a, b);
cout << "After SWAP-BY-REFERENCE, a = [" << a << "], b = [" << b << "]" << endl;
/*
* Reinitialize a, b.
*/
a = 13;
b = 111;
cout << endl << endl;
cout << "Before SWAP-BY-POINTERS, a = [" << a << "], b = [" << b << "]" << endl;
swap_by_pointers(&a, &b);
cout << "After SWAP-BY-POINTERS, a = [" << a << "], b = [" << b << "]" << endl;
int *pa = &a;
int *pb = &b;
cout << endl << endl;
cout << "Before SWAP-POINTERS, pa = [" << pa << "], pb = [" << pb << "]" << endl;
swap_pointers(&pa, &pb);
cout << "After SWAP-POINTERS, pa = [" << pa << "], pb = [" << pb << "]" << endl;
cout << endl << endl;
return 0;
}
Following is the compilation :
g++ swap.cpp -o swap
Following is the run :
./swap
Before SWAP-BY-REFERENCE, a = [42], b = [786]
After SWAP-BY-REFERENCE, a = [786], b = [42]
Before SWAP-BY-POINTERS, a = [13], b = [111]
After SWAP-BY-POINTERS, a = [111], b = [13]
Before SWAP-POINTERS, pa = [0x7ffcf0130770], pb = [0x7ffcf0130774]
After SWAP-POINTERS, pa = [0x7ffcf0130774], pb = [0x7ffcf0130770]