You can't have a variable number of variables in languages like C, so the compiler always knows where it put them. Thus it knows the right constant offset for every variable.
If you're talking about variadic functions like printf(char *, ...)
, then you have rules from the calling convention for how they're laid out, and you would normally increment a pointer. To index by arg-number, you need to know the width of all previous args. They're at least 8, but depending on the calling convention can be wider instead of using a hidden pointer in x86-64 System V. printf has conversions for long double
among other things (which is wider than 8 bytes), so it does have to support keeping track of which arg is where in case a conversion references an arg by number
If you're talking about using the stack as a stack data structure, with push / pop potentially inside loops, then you need to keep a pointer to know when your stack data structure is "empty", and further pops would eat into other local vars.
Having some of your local variables be variable-length arrays makes things trickier, like C int foo[n]
where n
is another variable. Many C compilers handle it by inventing a pointer to each VLA. The pointers have known fixed width so the compiler knows where to find them, and they can get initialized as space is reserved for the VLAs with sub rsp, rax
/ mov [rbp-16], rsp
for example.