calling functions & assembly code
Hi, I'm studying book "Thinking in C++", I suppose most of you have read it already.
In chapter 11 references & copy-constructor there is an interesting explanation of
function call with help of assembler code:
"To understand the need for the copy-constructor, consider the way C handles passing and returning variables by value during function calls. If you declare a function and make a function call,
int f(int x, char c);
int g = f(a, b);
how does the compiler know how to pass and return those variables?"
....
"If you figure out how to generate assembly code with your compiler and determine the statements generated by the function call to f( ), you’ll get the equivalent of:
push b
push a
call f()
add sp,4
mov g, register a"
It is pretty much clear to me what this represents except the following:
"The calling code is responsible for cleaning the arguments off the stack (which accounts for the add sp,4)"
What does this cleaning from the stack" mean? I'm not familiar with details of assembler but
I suppose add means adding so what is that all about cleaning? Those variables are supposed to stay on stack.
What instruction add sp,4 really means?
What is sp? Is it a name of CPU register?
Do you know any good introduction to assembler for C/C++ programmers(beginner/intermediate level)?
This is little confusing, so please help
Thank you very much for help!
Re: calling functions & assembly code
Quote:
Originally posted by Micko
push b
push a
call f()
add sp,4
mov g, register a"
It is pretty much clear to me what this represents except the following:
"The calling code is responsible for cleaning the arguments off the stack (which accounts for the add sp,4)"
What does this cleaning from the stack" mean? I'm not familiar with details of assembler but I suppose add means adding so what is that all about cleaning? Those variables are supposed to stay on stack.
The stack is a buffer the programs use to internally store values until needed. In the case of a function call, the parameters are added to the stack, then the function is called (the address of the call is also added to the stack)
Then within the routine, the parameters are looked at and used. The function returns. Now you need to take the parameters off the stack, that's done to "clean up" from the function call. In effect, the parameters added are deleted or removed.
Quote:
Originally posted by Micko
What instruction add sp,4 really means?
What is sp? Is it a name of CPU register?
Yes, the Stack Pointer is one of the registers.
The code add sp,4 actually adds the value 4 to the stack, which removes the values added before the call.
Quote:
Originally posted by Micko
Do you know any good introduction to assembler for C/C++ programmers(beginner/intermediate level)?
http://win32asm.cjb.net/ has some stuff. Do a search for more.