Archived

This topic is now archived and is closed to further replies.

31337

The Stack, Local Variables, and Mid-Function Creation

Recommended Posts

I have a question concerning C, C++, and assembly regarding local variables. Consider the following C program: void Whatever { int x = 1; DoWhateverYouWant(); } If DoWhateverYouWant() doesn''t have a problem with it, in C++ this program could be rewritten: void Whatever { DoWhateverYouWant(); int x = 1; } Notice the only difference is the position of the declaration of x. Now, consider the first version written in x86 assembly. It probably looks something like this: Whatever PROC push ebp ; Save ebp mov ebp, esp ; Move the stack pointer into ebp sub esp, 4 ; Make room on the stack for x mov [esp], 1 ; Initialize x to be 1 ; DoWhateverYouWant goes here mov esp, ebp ; Restore the stack pointer pop ebp ; Restore ebp Whatever ENDP My question is that when you take the C++ route, do most compilers end up doing the following? Whatever PROC ; DoWhateverYouWant goes here push ebp ; Save ebp mov ebp, esp ; Move the stack pointer into ebp sub esp, 4 ; Make room on the stack for x mov [esp], 1 ; Initialize x to be 1 mov esp, ebp ; Restore the stack pointer pop ebp ; Restore ebp Whatever ENDP The reason I ask is that the LOCAL directive in assembly language can only come after the function declaration, but this doesn''t make much sense considering the second portion is (somewhat) legitimate code. Thanks

Share this post


Link to post
Share on other sites
From what I''ve seen, compilers allocate space for all automatic variables in a function at the beginning of the function, regardless of their scope or their location in the function.

Share this post


Link to post
Share on other sites
"allocation" of the required space for the function is done at the beginning..

the initialisation is done at the line int i = 0, or similar.. thats where the constructor gets called.

"take a look around" - limp bizkit
www.google.com

Share this post


Link to post
Share on other sites