Function call sequence points
What you'll learn: Why the C compiler must finish all calculations within a function's arguments before the function actually starts running.
The "Everything in its Place" Rule
In C, a function call is a major milestone in your code’s execution. Before a function can do its job, the computer needs to prepare all the ingredients (arguments) you’re sending to it. The moment just before the function starts is called a sequence point.
Think of it like a professional kitchen. A chef (the function) can’t start a stir-fry until the sous-chef has finished chopping all the vegetables. It doesn’t matter if the sous-chef chops the carrots first or the onions first, but they must all be chopped and sitting in bowls before the heat is turned on. In C, the "chopping" is the evaluation of expressions, and the "turning on the heat" is the function call.
Why Sequence Points Matter
A sequence point is a guarantee. It promises that every "side effect" (like incrementing a variable with ++ or assigning a value with =) within the function’s arguments will be fully completed before the function's first line of code executes.
Without this rule, your program might try to use a variable while it is still in the middle of being changed, leading to unpredictable bugs.
Seeing it in Code
Consider a scenario where we pass an incrementing variable to a function:
#include <stdio.h>
void display_age(int age) {
printf("The age is: %d\n", age);
}
int main() {
int my_age = 25;
// The sequence point occurs after (my_age++) is fully resolved.
// The side effect (incrementing to 26) is guaranteed to happen
// before display_age begins.
display_age(my_age++);
printf("Back in main, age is now: %d\n", my_age);
return 0;
}
In this example, the expression my_age++ has a value (25) and a side effect (changing the variable to 26). The sequence point ensures that by the time display_age starts, my_age has officially become 26 in the computer's memory.
A Note on Order
While the sequence point guarantees everything is finished before the function starts, it does not guarantee the order in which multiple arguments are handled. If you call add(x++, x++), C doesn't promise which x++ happens first—only that both will be finished before add begins. Because of this, it is best practice to avoid changing the same variable twice in the same function call.
Key takeaway
A function call acts as a boundary; all calculations and variable changes in the arguments must be 100% complete before the function begins.