Tuesday, February 26, 2019

memory - Automatic variables in C++

C++ does not have the concept of a stack or heap, it is an implementation detail as far as the language is concerned.


That being said, every implementation I know of uses the stack to manage the lifetime of local variables. However, many local variables may end up living entirely within registers and never touch the stack, and some local variables may be optimised out completely. Just because you declare an automatic variable doesn't mean that it will be put on the stack.


e.g.


int main()
{
int x = rand();
int y = 2;
cout << x << y << endl;
return 0;
}

In this code, with optimisations on, the variable y will almost certainly be removed completely and variable x will probably be given its own register. It's unlikely that either of those variables will ever exist on the stack.

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...