C functions and pointer parameters
Modify caller-owned values through valid addresses.
On this page
Functions, addresses, and pointer dereferencing.
- Modify caller-owned values through valid addresses.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
C passes arguments by value, including pointer arguments. Copying an address into a parameter still lets the function access the original object at that address.
swap saves one value before overwriting either object. Both pointers must point to live, writable int objects.
Code example
#include <stdio.h>
#include <assert.h>
void swap(int *a, int *b) {
int temporary = *a;
*a = *b;
*b = temporary;
}
int main(void) {
int x = 3, y = 8;
swap(&x, &y);
printf("%d %d\n", x, y);
swap(&x, &x);
assert(x == 8 && y == 3);
return 0;
}8 3
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <stdio.h>#include <assert.h>void swap(int *a, int *b) { int temporary = *a; *a = *b; *b = temporary;}int main(void) { int x = 3, y = 8; swap(&x, &y); printf("%d %d\n", x, y); swap(&x, &x); assert(x == 8 && y == 3); return 0;}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create the caller's variables. | x = 3, y = 8 | — | |
| Pass copies of their addresses. | a = &x, b = &y | — | |
| Save x before overwriting it. | temporary = 3 | — | |
| Write y into x. | x = 8, y = 8 | — | |
| Write the saved value into y. | x = 8, y = 3 | — | |
| Print the swapped values. | x = 8, y = 3 | 8 3 | |
| Swapping an object with itself leaves it unchanged. | x = 8, y = 3 | 8 3 |
Behind the scenes
How C processes this code
The C compiler produces a native program. Variables occupy memory, and execution enters main.
Cost and common mistakes
O(1) time and auxiliary space.
- Dereferencing NULL or a dangling pointer is invalid.
- Swapping plain int parameters would only change local copies.
Try it yourself
Trace swapping x=5 and y=5.
Reveal answer and reasoning
The temporary is 5, both assignments store 5, and the two values remain equal.