C Functions Explained Visually: Calls, Parameters and Returns
Step through a function call from main to add and back again. See when parameters are created, how the return value is calculated and where execution resumes.
Explore the complete interactive C functions lesson →Start with working C code
The call add(3, 4) passes 3 and 4 by value; the function returns 7, which main stores in result.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main(void) {
int result = add(3, 4);
printf("%d\n", result);
return 0;
}
Interactive function-call visualization
Use the controls to follow the C example above. The labels describe the current model state.
The explanatory material on this page is also available without JavaScript. Enable JavaScript to use the visual step controls.
Ready to explore the example.
What happens during a function call?
When main calls add(3, 4), execution enters add. Its parameter variables a and b receive the values 3 and 4. The expression a + b evaluates to 7, then return sends the value to the caller.
The diagram is a conceptual call-stack trace. Exact compiler optimizations and physical stack layout may differ, but the sequence of evaluation and return value is the important concept.
Pass by value in C
Ordinary function parameters are initialized with copies of argument values. Changing a inside add does not change a separate variable in main. To modify an existing object owned by the caller, a function can receive a pointer to that object and dereference it safely.
The int before add declares its return type. The parameter types are written inside parentheses. A function declaration or definition must be visible before the function is called.
Exercises
- Predict the output of
printf("%d", add(5, 2));. - What values do
aandbreceive foradd(9, 1)? - Explain what happens to the call's parameters after
return.
Answers
The first expression prints 7. In the second call, a is 9 and b is 1. After the function returns, those parameter objects no longer remain accessible through that completed call.