Pointers as Parameters
A function can take a pointer too. It then has the address of a variable and can change the variable through *. This is how programs in C pass variables to functions: C++ grew out of the C language, which has no references. That's why you will see this style in older code and in many libraries:
#include <iostream>
void addPoint(int* points) {
*points = *points + 1;
}
int main() {
int score = 10;
addPoint(&score);
std::cout << "Score: " << score << std::endl;
return 0;
}This prints:
Score: 11Compare it with the function addPoint from the first page of the lesson, which had the parameter int& points. Now the parameter has the type int*, inside the function you write * before it, and the call passes an address: addPoint(&score). The advantage is that the call itself shows that the function may change score. The downside is more symbols and more chances to make a mistake.
Common mistakes:
- A call without
&,addPoint(score), ends with the errorno matching function for call to 'addPoint'and the notecandidate function not viable: no known conversion from 'int' to 'int *' for 1st argument; take the address of the argument with &. The compiler even tells you what to do: pass the address with&. - The other way round, when a function wants a reference and you pass it an address, the note ends with
remove &. - When you forget the asterisk inside the function and write
points = points + 1;, the program compiles without an error, but it changes the address stored in the pointer, not the score. The variablescorestays10.
Instructions
- 1
In a game, you can buy a life for 100 coins. In place of the first comment, write a function
buyLifewith two parameters of typeint*: the pointerslivesandcoins. Through the pointers, the function subtracts 100 coins and adds one life. - 2
In
main, callbuyLifein place of the comment before the first print line, and pass it the addresses of the variableslivesandcoins. The program printsLives: 4, coins: 50twice. - 3
You can only buy a life when you have at least 100 coins. Add a condition to the function: when the player has fewer than 100 coins, the function changes nothing and prints
Not enough coins. Then callbuyLifea second time, in place of the last comment. The program printsLives: 4, coins: 50, thenNot enough coinsand thenLives: 4, coins: 50again.