I just read this question: Why are different case condition bodies not in different scope?
It’s a Java question, but my question applies to both C# and Java (and any other language with this scope reducing feature).
In the question, OP talks about how he knows he can manually add in {} to refine the scope of each case in the switch. My question is, how does this work? Does it go up the stack as if it were a method call? If so, what does it do so that it still have access to other variables declared before this scope?
All it’s doing is defining another scope, it’s not translated into a method call. Remember that for locals, the CLR/JVM could decide not to use stack space for them at all, it could choose to utilise processor registers. In some cases, if you’ll excuse the pun, it could decide to optimise out some of the locals by virtue of them not being needed. It could even decide that it can use one register, or memory location “on the stack” for multiple variables as they’re never going to overlap.
Taking the example from the linked question:
As it stands, that code is functionally identical to:
As the
accountvariable is never used in multiple cases, which means it’s an ideal candidate (in this simplistic example ) for using a register or a single space in memory.