Function Parameters and Calling Conventions
What You'll Learn
You'll understand how programs pass data to functions and how standard calling conventions ensure functions work together correctly.
The Challenge of Passing Data
When you call a function in assembly, you need to give it information (parameters) and get results back. But how does the calling code communicate with the function? There are two main approaches: registers and the stack.
Passing Arguments via Registers
The fastest method is to place arguments directly into agreed-upon registers. For example, a calling convention might say "put the first argument in register R1, the second in R2." This is like handing someone items directly—quick and efficient.
MOV R1, 5 ; First argument
MOV R2, 10 ; Second argument
CALL AddFunc ; Function reads from R1 and R2
The downside? You're limited by the number of registers available.
Passing Arguments via the Stack
For functions with many parameters, you push arguments onto the stack before calling. The function then reads them from known stack positions. This is like leaving items in numbered mailbox slots—unlimited capacity but slightly slower.
PUSH 10 ; Second argument
PUSH 5 ; First argument
CALL AddFunc ; Function accesses via stack offsets
Calling Conventions: The Rules Everyone Follows
A calling convention is a standard agreement about:
- Where arguments go (which registers or stack order)
- Where return values are placed (typically a specific register)
- Which registers the function can modify vs. must preserve
- Who cleans up the stack after the call (caller or callee)
Common conventions include cdecl, stdcall, and platform-specific ABIs. Following these rules ensures your functions can call library code and vice versa.
Key Takeaway: Function parameters flow through registers (fast, limited) or the stack (flexible, slower), and calling conventions are the shared rules that make function calls work reliably across different code.