What a C function actually receives
Distinguish value parameters from pointer-based updates and array parameters.
After this lesson
You should be able to
- Predict whether a function can modify a caller's object.
- Pass an array together with the bound required to process it.
C passes arguments by value
Every C parameter receives a value. For int x, the value is an integer copy; changing x does not change the caller's variable. For int *p, the copied value is an address, and dereferencing that address can change the caller's object.
This is often described as achieving reference-like behavior through pointers. It is still pass-by-value: the pointer itself is copied. Check for null when null is permitted, and document whether the function reads or modifies the pointed-to object.
void swap_ints(int *a, int *b) {
int temporary = *a;
*a = *b;
*b = temporary;
}
swap_ints(&left, &right);An array parameter needs a bound
In a function parameter, int values[] is adjusted to int *values. The function does not receive the built-in array's length. Pass count separately and keep every access below it.
Use const int values[] when the function promises not to modify elements. const improves the contract and lets the compiler catch accidental writes.
int sum_array(const int values[], size_t count) {
int total = 0;
for (size_t i = 0; i < count; i++) {
total += values[i];
}
return total;
}Try it yourself
Write a function that sets an integer to zero through a pointer and safely ignores null.
Need a hint?
Test the pointer before dereferencing it.
Check the worked solution
The caller passes the variable's address with &.
void reset(int *value) {
if (value != NULL) {
*value = 0;
}
}Quick check
Why must an array count usually be a separate parameter?
Why this lesson exists
Syllabus mapping
Value parameters · Array parameters · Pointer parameters · Idea of reference
Maps to course outcomes CO3, CO4, CO5.