c.***********@gmail.com wrote:
Is there any memory allocated in stack when declaring a function
e.g void fun(int a,int b,int c);
What stack?
The code isn't running, so even if there's a stack at runtime,
there isn't one when the declaration gets processed by the
compiler.
(Unless you're asking about the /compiler's/ stack, if any; if
so, why?)
Is it true that compiler reserves 3 stack spaces for parameters a ,b
and c....
No.
When the compiler processes that /declaration/, it needn't reserve
stack space for anything. The declaration just says "there's this
function `fun` with arguments `(int, int, int)` and return-type void."
Whether arguments are passed on a stack or not doesn't matter, since
we're not compiling a call of `fun` or a definition of it either.
When we compile `void fun(int a, int b, int c) { ...the body ... }`,
/then/ we might think about stack allocation, if that's how the
implementation operates. What's /required/ is that the code behaves
as if there's three auto variables a, b, c, initialised to the values
passed in a call, and which can be forgotten when the function exits.
Consider
int fun( int a, int b, int c ) { return a + b + c; }
where I've returned `int` to have something happening. When the
compiler compiles this code it need not use any stack /at all/,
not even a bit:
add r0, r1
add r0, r2
mov pc, r14
The arguments are passed in registers r0, r1, and r2, and the
result returned in r0. The addition can be done in-place into
the result/first-argument register. Since `fun` doesn't call
anything else, we don't need to stack a return address or copies
of the arguments.
So, while an implementation /might/ use a stack for function
business, specific cases can be stack-free.
The moral of the stoty is that one shouldn't confuse an
implementation technique (stacks) with a specification (variables
which vanish when their scope is left), nor declarations (let
me tell you about X) with definitions (compile me this X) and
executions (call X and pass these three values).
--
"It's just the beginning we've seen." - Colosseum, /Tomorrow's Blues/
Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN