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

查看:1122
本文介绍了为什么不能在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.

(你可能想争辩,我只能在第二个中声明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天全站免登陆