Reputation: 31
void main() {
int a = 10;
int b = 37;
swap(&a, &b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
void swap (int* a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Hi I have a program like this . I want to paint a picture that describes in detail the call stack but I don't know if I understood it properly. Give me advice and can you fix if i wrong?
| local of spam() *b=temp |
| local of spam() *a=*b |
| local of spam() <int> temp=*a |
| Local variables adress of a, b| // example 0x100 a , 0x102 b
| return adress of swap() |
| call Swap |
| Parameter a,b |
| Local variables a =10 ,b = 37 |
Upvotes: 1
Views: 189
Reputation: 106116
You've got the right general idea, but the details depend on the implementation - they're not specified in the C++ Standard itself, and they can also vary with compiler optimisation settings. Many of the things you're expecting on the stack may simply be put in CPU registers (and indeed the calling conventions used by a compiler may mandate that it passes certain arguments to functions via registers, and others via the stack). Only data goes on the stack, not operations.
Still, as I said you're generally imagining it well enough for the purposes of a general mental model for high level programming. What's not quite right in your model is:
"return address of swap()
" / "call Swap
" -> chronologically, the next address in the calling function that will need to be executed when the called function returns would normally be preserved somewhere (the stack, or a specific register) either before the call is made (especially common if there's no CPU call
instruction, and a jump
instruction is actually used), or by the CPU's call instruction itself
call Swap
altogetherthere may be other CPU registers to preserve before or as the call is made too, or on some CPUs there are "windows" of CPU registers that calls shift into and out of as calls are made and they return; lots of minor variations but of little importance to your high level understanding as a C++ programmer
"local of spam() *a=*b
" / "local of spam() *b=temp
" there will be no stack usage associated with the assignment there; you've already mentioned that the addresses may be passed via the stack in "Local variables adress of a, b
"
(If you want more real insights, use a debugger like gdb to examine the stack throughout your program's execution).
Upvotes: 2