为什么不能在 if 语句中声明变量? [英] Why can't variables be declared in an if statement?

查看:29
本文介绍了为什么不能在 if 语句中声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 Java 代码无法编译.

The following Java code does not compile.

int a = 0;

if(a == 1) {
    int b = 0;
}

if(a == 1) {
    b = 1;
}

为什么?没有代码路径导致程序将 1 分配给 b 而不先声明它.

Why? There can be no code path leading to the program assigning 1 to b without declaring it first.

我突然想到 b 的变量范围可能仅限于第一个 if 语句,但后来我不明白为什么.如果我真的不想为了提高性能而不必要地声明 b 怎么办?我不喜欢变量在声明后未被使用.

It occurred to me that b's variable scope might be limited to the first if statement, but then I wouldn't understand why. What if I really don't want to declare b needlessly, in order to improve performance? I don't like having variables left unused after declaration.

(你可能想争辩说我可以在第二个 if 语句中简单地声明 b,在这种情况下,想象它可能在其他地方的循环中.)

(You may want to argue than I could simply declare b in the second if statement, in that case, just imagine that it could be in a loop somewhere else.)

推荐答案

为什么?没有代码路径导致程序将 1 分配给 b 而不先声明它.

Why? There can be no code path leading to the program assigning 1 to b without declaring it first.

你说得对,但编译器不知道.编译器不执行代码.编译器只转换为字节码而不计算表达式.

You are right, but the compiler doesn't know that. The compiler does not execute the code. The compiler only translates to bytecode without evaluating expressions.

这篇关于为什么不能在 if 语句中声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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