Pointers and References in C++ (Part II)

Diane Khambu
2 min readOct 10, 2023
geezz, these geese, no cheese © Diane Khambu

Did some handy exercises in pointers and references. Was fun, so you can try as well.

0) Write a function that swaps two integer values using call-by-reference.

#include <iostream>
using namespace std;

void swap(int &a, int &b){
int tmp = a; // store reference a's value
a = b; // update a's value to b's value
b = tmp; // update b's value to tmp
}

int main() {
int a = 5;
int b = 10;
swap(a, b);
cout << a << ", " << b << endl; // prints 10, 5

return 0;
}
  1. Rewrite your function to use pointers instead of references.
 #include <iostream>
using namespace std;

void swap(int* a, int* b){
int tmp = *a; // store pointer a's value
*a = *b; // update pointer a's value to the value of pointer b's
*b = tmp; // update pointer b's value to the tmp
}

int main() {
int a = 5;
int b = 10;
swap(&a, &b);
cout << a << ", " << b << endl; // prints 10, 5

return 0;
}

2) Write a function similar to the one in part 1, but instead of swapping two values, it swaps two pointers to point to each other’s values. Your function should work correctly for the following example invocation:

int x = 5, y=6;
int* ptr1 = &x, *ptr2 = &y;
swap(&ptr1, &ptr2);
cout << *ptr1 << ", " << *ptr2 << endl; // prints 6, 5

Ok, we’ll be seeing pointer of pointer.

#include <iostream>
using namespace std;


void swap(int** a, int** b){
int* tmp = *a; // store pointer a is pointing to
*a = *b; // change value a is pointing to b's values
*b = tmp; // update value b is pointing to tmp
}

int main(){
int x = 5;
int y = 6;

int* ptr1 = &x;
int* ptr2 = &y;

swap(&ptr1, &ptr2);
cout << *ptr1 << ", " << *ptr2 << endl; // ptring 6, 5
}

Short and nifty exercises to bolster your C++’s fundamentals!

See you in my next post. Until then, ✨.

Inspiration:

You can support me on Patreon!

--

--