Unassigned local variable mystery

陌路散爱 提交于 2021-02-17 07:05:19

问题


    int x;
    if (Q())
        x = 123;
    if (R())
        Console.WriteLine(x); // illegal

    int x;
    if (Q())
        x = 123;
    if (false)
        Console.WriteLine(x); // legal!!

May I know why second one is legal while former one is throwing 'using unassigned local variable' compile time exception?


回答1:


This tells compiler that the condition under if in the statement given below will never execute, so the constraint of unused variable does not apply to it.

if (false)
        Console.WriteLine(x); // legal!!



回答2:


Because the second one is eliminated by compiler as never executed.




回答3:


If Q() == FALSE and R() == true, x is not set and it will try to use it.



来源:https://stackoverflow.com/questions/11071682/unassigned-local-variable-mystery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!