C Pointers and Functions
Pass by reference means a function receives the address of a variable. Pointers so far read and changed values in main; this lesson hands the address to a function, so the function can change the original.
A copy leaves it unchanged
score reaches the function as a copy. The function prints 11 from its copy, and the original score stays 10.
#include <stdio.h>
void try_change(int x) {
x = x + 1;
printf("%d\n", x);
}
int main() {
int score = 10;
try_change(score);
printf("%d\n", score);
return 0;
}An address changes the original
score reaches the function as an address. The function adds 10 to the original value, so the print shows 20.
#include <stdio.h>
void add_ten(int *n) {
*n = *n + 10;
}
int main() {
int score = 10;
add_ten(&score);
printf("%d\n", score);
return 0;
}Set a value inside
count reaches the function as an address. The function sets the original value to 0, so the print shows 0.
#include <stdio.h>
void set_to_zero(int *n) {
*n = 0;
}
int main() {
int count = 5;
set_to_zero(&count);
printf("%d\n", count);
return 0;
}Example
#include <stdio.h>
void double_it(int *n) {
*n = *n * 2;
}
int main() {
int value = 21;
printf("%d\n", value);
double_it(&value);
printf("%d\n", value);
return 0;
}Key points
- A function that takes a plain int gets a copy of the value.
- Changing the copy inside the function leaves the original unchanged.
- A function that takes a pointer gets the address of the variable.
- With the address, the function can change the original variable.
- void add_ten(int *n) takes the address of an int.
- Call it with add_ten(&score); to pass the address of score.
- Inside the function, *n reads and changes the original value.
value starts at 21. The first print shows 21. The call passes the address of value to double_it, and the function doubles the original value. The second print shows 42.
Note
Passing score instead of &score hands over a copy, so the original stays unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How can a function change a variable that lives outside it?