开发者

Local variable scope

I would like to have some geek advice here since I can’t brainstorm more.

class sampleType
    {
        public void M1(bool someValue)
        {
            if (someValue)
            {
                int a = 1;
                Console.WriteLine(a);
                goto comehere;
            }
            else
            {
                int a = 2;
                Console.WriteLine(a);
                goto comehere;
            }

        comehere:
            {
                int a = 3;
                Console.WriteLine(a);
            }
        }
    }

Assumption: M1 is 开发者_JS百科jitted and ready to execute. M1 is the last item in the thread stack (last register).

Question: How current stack register denote local variables of M1? Especially scope of ‘a’ at if/else/goto block.


At the IL level, either:

1) The three non-overlapping local variables "a" will be generated as a single temporary storage slot and re-used; we know this is safe because they do not overlap, they are all the same type, and they have the same name, so there is no chance the debugger will get confused about them. or:

2) The three local variables "a" will be generated as three different temporary storage slots, or

3) The three local variables "a" will be determined to be single-assignment and side-effect-free constants, and logically turned into constants, not variables. I do not believe we perform this optimization at this time but we reserve the right to in the future.

At the jitter level, the jitter is free to do whatever it pleases. It can generate a single stack slot. It can assign a single register. It can generate multiple stack slots, it can assign multiple registers. It can treat them as constants. What the jitter can do is limited only by the cleverness of the jitter team. There is no requirement whatsoever that this uses any stack at all.


It's not clear to me what you're trying to determine - what the C# language guarantees in terms of behaviour, what the compiled IL will look like, or what the JIT-compiled native code will look like.

In terms of IL, I'd expect these to end up as separate local variables in the method metadata. It's possible that the JIT will notice that it can manage with a single stack allocation and reuse it for all three variables. However, you should neither know nor care whether that happens. The three a variables are logically distinct and will not interfere with each other.

(If that doesn't answer your question, please clarify exactly what you're trying to determine...)


As Eric Lippert writes: The Stack Is An Implementation Detail. How local variables are mapped to the stack depends on the jitter implementation. It's not specified by the language.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜