C++ Function Call vs. New Blocks for Push/Popping on the Stack
I was reading about variable scope in C++ and encountered an interesting block structure:
int main(int argc, char **argv) {
int local;
{ // New level of scope
int more_local;
}
return 0;
}
I understand that variables are popped out of the stack at the end of each block denoted by the closing curly brace }
.
I've also read that function calls also push their variables on the stack and terminate at the end of the call denoted by closing curly brace }
:
void foo() {
int more_local;
}
int main(int argc, char **argv) {
int local;
foo();
return 0;
}
How is the stack handled differently in both situations and what are the advantages and disadvantage of both?
Well, you could say that your first example could be seen as an inlined function. :P
But generally, function calls and opening a new scope
have nothing to do with each other.
When you call a function, the return address and all arguments are pushed on the stacked and popped from it after the function returns.
When opening a new scope
, you simple call the destructor of all objects within that scope at the end of it; it is by no means guaranteed that the actual space occupied by those variables is popped from the stack right away. It could, but the space could also simply be reused by other variables in the function, depending on the compilers / optimizers whims.
With the function call, you are pushing the return address onto the stack and creating a new stack frame. If you just enclose parts of code in curly braces, you are defining a new scope, as you said. They are just like any block of code following a control statement such as if, for, while, etc.
You can't really talk about advantages and disadvantages here, because these are two completely different things. There aren't very many situations where you will benefit from enclosing blocks of code in curly braces, and it can make code harder to read.
int more_local;
will be placed on the stack in both cases. But second scenario will have an overhead of function call.
I would suggest you to think about rather this:
void foo()
{
int local;
{ // New level of scope
int more_local_1;
}
{ // New level of scope
int more_local_2;
}
}
Here more_local_1
and more_local_2
may share the same memory location. Once it used for more_local_1
and in second scope for more_local_2
variable.
上一篇: 了解堆栈数组实现(C)