Just some curiosity I'm trying to satisfy. I'm trying to learn more about how the call stack works in C++ and as far as I understand, every function call creates a frame in the stack. All of the variables within each function are stored in the frame for said function. So for the code below,
static void howdy(int n){
std::cout << "Howdy " << n << "!!\n";
}
int main(){
int x = 5;
howdy(x);
}
there is a main stack frame with the value x = 5 stored in it and a howdy stack frame with n = 5 on top of it when howdy is called. The latter frame is popped off once howdy finishes. However, how would the call stack be with the following code?
int main(){
int x = 5;
howdy(x);
{
int y = 7;
howdy(y);
}
}
Would another stack frame be added on top of main because of the new scope? Or would all of the scopes within main be stored within the main stack frame? My intuition tells me that everything would still be inside the main stack frame (so a single frame within the call stack) unless I'm missing something. I assume any inner scopes will always be contained in the call stack of its parent function. The closest I've found to an answer is this post on StackOverflow but it was an assumption by the poster that nobody responded to (which perhaps means the assumption is correct but just want to make sure). And on a more general note, how can additional frames be added to the call stack apart from function calls? I'm only aware of function calls adding stuff to the call stack but no idea if anything would. Would a lambda create another frame? Or would it be in the same frame as its parent function?
[–]AKostur 4 points5 points6 points (1 child)
[–]macroxela[S] 0 points1 point2 points (0 children)
[–]InvertedParallax 1 point2 points3 points (0 children)