4

I am read a passage about stack. But I don't understand the following sentence: Since the stack grows down, the first parameter will be stored at the lowest address (this inversion of parameters was historically used to allow functions to be passed a variable number of parameters).

My question is: I think even if the parameters are not inversion-ly stored, we can still allow to pass a variable number of parameters. For example, sp = sp - 4, then we push the first parameter's value onto the stack, then we do another sp = sp - 4 and push second parameter and so on.

Thanks!

Tony Lucas
  • 189
  • 1
  • 13
  • 1
    You're absolutely right. The nature of the stack is irrelevant. See my answer to a similar question https://stackoverflow.com/questions/56952717/how-does-variable-length-argument-works-in-c/56954307#56954307 – Frankie_C Aug 04 '19 at 20:47

1 Answers1

2

The thing is: the function must know where the 1st parameter is, not how many parameters there are.

Imagine you have

void fx(int, ...);

and

fx(2, -1, 42) /* 2 indicates 2 more arguments */;
fx(5, -1, 42, 2, 2, 2);

Imagine the stack (growing in whatever direction you want) has "X Y" before the call.

If pushed in reverse the stack becomes "X Y 42 -1 2" or "X Y 2 2 2 42 -1 5" and it's easy for the code to pick up the first argument: the thing at the top of the stack.

pmg
  • 106,608
  • 13
  • 126
  • 198