Menu
Coddy logo textTech

Pointers as Parameters

Lesson 7 of 14 in Coddy's C++ Pointers course.

The usage of functions when programming is widespread. We use them as a tool to complete a task multiple times, or if not at least to organize our code and have it separated. 

When we pass values to a function, the values we operate within the function are copies of the original values. That's where passing values as pointers to a function come in handy.

void swap(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
    cout << x << " " << y << endl;
}

int main() {
    int a = 10, b = 20;
    cout << a << " " << b << endl;
    swap(a, b);
    cout << a << " " << b;
}
Output:
10 20
20 10
10 20

As you can see, initially the values are normal, when we pass them to the functions, copies of the original values are made, the copies are switched we print out the switched values and finally we can see that after the function call in the main function we don't get permanent results and the values are normal. This can be solved by using pointers

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
    cout << *x << " " << *y << endl;
}

int main() {
    int a = 10, b = 20;
    cout << a << " " << b << endl;
    swap(&a, &b);
    cout << a << " " << b;
}
Output:
10 20
20 10
20 10

We have solved the problem. Now, instead of passing values, we pass addresses of where the values are, as arguments in the function we take pointers holding those addresses. We create an integer temp, that takes the value dereferenced from x, the value at the address of x (which is the same address as a in the main() function) is changed to the value of y (the initial value from the address of b) and finally y dereferenced takes the value of temp. Because we changed the values at the given addresses, not the given values, we have a permanent change.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Finish the function Calculator that permanently changes the values of the variables large and small, subtract large by the difference between large and small, while small should be multiplied by itself.

Input
5 3

Output
5 3
3 9

Explanation
Subtracting 5 by the difference between 5 and 3 which is 2, is 5 - 2 = 3, while multiplying 3 by itself gives us 9

Note: Do NOT write the main() function

Try it yourself

#include <iostream>

using namespace std;

void Calculator(// Take arguments: large & small) {
    // Enter code for calculations
}


// Do NOT write the main() function

All lessons in C++ Pointers