未分配的局部变量之谜 [英] Unassigned local variable mystery

查看:95
本文介绍了未分配的局部变量之谜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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?

推荐答案

这告诉编译器,以下给出的语句中if条件将永远不会执行,因此未使用变量的约束

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!!

这篇关于未分配的局部变量之谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆