Reputation: 1922
Does below function need any stack for execution?
int a;
void func(void)
{
a = 10;
}
Upvotes: 0
Views: 225
Reputation: 223264
As long as a C compiler can see the definition of func
, it can1 implement func
without using any stack space. For example, where it sees a call to func
, it can implement that by emitting an instruction or two to move 10 into a
. That would achieve the same result as calling func
as a subroutine, so the C rules permit a C implementation to implement a call to func
in that way, and it does not use any stack space.
Generally, if the compiler could not see the definition of func
, as when compiling another source file that calls func
but does not define it, the compiler would have to issue a call instruction or something similar, and that would, at the least, push the return address onto the stack.
Additionally, if the routine being called were more complicated, the compiler might choose not to implement it inline or might not be able to do so. (For example, if func
contained calls to itself, it is generally not possible for the compiler to implement it with inline code in all situations; the compiler will need to implement it with actual subroutine call instructions, which do use stack space.)
1 Whether any particular compiler will implement func
without using stack space is another matter, dependent on the compiler, the switches used to compile, and other factors.
Upvotes: 2