Search code examples
c++stackblockfunction-calls

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?


Solution

  • 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.