Pointers
Use addresses to let a function update variables that belong to its caller.
Complete program
#include <stdio.h>
void swap(int *left, int *right) {
int temporary = *left;
*left = *right;
*right = temporary;
}
int main(void) {
int a = 10, b = 20;
printf("Before: %d %d\n", a, b);
swap(&a, &b);
printf("After: %d %d\n", a, b);
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
The arguments are addresses of live int objects. The parameters receive copies of those addresses, and dereferencing them accesses the caller’s objects.
This function assumes both pointers are valid and writable. Passing NULL or an address whose object has expired violates that contract. Compare with a function taking two plain int parameters: assigning those copies would not swap the originals.
Expected output
Before: 10 20
After: 20 10Concepts to practice
- Address-of
- Dereferencing
- Pass by value
- Object lifetime
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.