Nearby lessons
75 of 124C - Function Parameters
Parameters are the variables in a function's header that receive incoming values. Learn how to declare them, pass arrays and pointers as parameters, use const to protect inputs, and write a function that takes nothing.
Every Parameter Needs Its Own Type
Unlike variable declarations, you cannot share a type across parameters:
Parameters Are Local Variables
A parameter behaves exactly like a local variable that was initialised from the argument. You can even reassign it — the caller is unaffected:
Array Parameters Decay to Pointers
An array parameter is really a pointer. That is why sizeof inside the function gives the pointer size, and why the size must be passed separately:
Arrays Are Effectively Passed by Reference
Because the function receives the address, changes to the elements are visible to the caller:
const Parameters — A Promise Not to Modify
Marking a pointer parameter const documents your intent and lets the compiler enforce it:
Pointer Parameters — Modifying the Caller
To let a function change a caller's scalar variable, pass its address and take a pointer parameter:
Returning Several Values
A function returns one value — but with pointer parameters it can hand back as many as you need:
Struct Parameters
A struct is copied whole by default. For anything large, pass a const pointer instead to avoid the copy:
2D Array Parameters
Every dimension except the first must be specified so the compiler can compute row offsets:
Common Mistakes
| Mistake | Problem |
|---|---|
f(int a, b) | b has no type — compile error |
sizeof(a) on an array parameter | Gives the pointer size, not the array size |
| Forgetting the size parameter | The function cannot know where the array ends |
| Passing a value where a pointer is expected | The address is treated as a value |
| Omitting the second dimension of a 2D parameter | Compile error |
| Passing a huge struct by value | Slow — copies every byte |
void f(int a[10]) looks like it enforces ten elements. It does not — the 10 is ignored and the parameter is still just int *. Nothing stops a caller passing a 3-element array. The size must travel as a separate argument.- Each parameter needs its own type: (int a, int b), not (int a, b).
- Parameters are local variables initialised from the arguments.
- An array parameter decays to a pointer — pass the size separately.
- const on a parameter promises the function will not modify it.
- Use (void) when a function takes no parameters.