I may be remembering incorrectly, but I'm sure that in C++ you could declare two variables of the same name where the second declaration is within it's own code block. E.g.
Expand|Select|Wrap|Line Numbers
- void myfunction()
- {
- int x = 5;
- //some code
- {
- int x = 3;
- //print x
- }
- //print x
- }
If this is correct, my question refers to the compiler and stack allocation.
I found out the other day that Java allocates memory for all local variables within a function block, regardless of whether the code actually reaches those declarations. Apparently, this is to make the compiler/runtime easier to code and manage. I'm assuming this is the reason you can not have a situation similar to the above code example in Java, as you would have two local variables by the same reference being allocated to the stack at the same time.
I wondered if this was the way all languages handled memory allocation. If this is the case in C++, my question is how does C++ allow two variables to be allocated to the same named reference within a function block? Does C++ allocate to the stack each time it enters any kind of code block? Or do pseudo/mask references get used, whereby the first x is internally considered as x1 and the second as x2?
Or something...
I have not a lot of knowledge on this area of coding, but it's something I've recently started wondering about for the purposes of memory optimization in my coding.
Regards,
Rob.