在C和Java中的局部变量

huangapple go评论79阅读模式
英文:

Local variables in C and Java

问题

我知道C和Java使用词法作用域,变量的作用域限定在定义它的代码块内。看一下Java的代码示例:

public class Main
{
    public static void main(String[] args) {
        int j = 0;
        while(j==0){ 
            int j =1;
            System.out.println(j);
        }
    }
}

这个程序会报错,提示"variable j is already defined in method main"。

再来看一下C的代码示例:

#include <stdio.h>

int main()
{
    int j = 0;
    while(j==0){ 
        int j =1;
        printf("%d",j);
    }
}

在这里,我们会得到一个无限循环,输出"11111111.............."。

为什么C编译器不像Java那样对变量j报错呢?

英文:

I know C and Java uses lexical scoping and the scope of a variable is within the block where it was defined.
See the code of Java:

public class Main
{
	public static void main(String[] args) {
		  int j = 0;
          while(j==0){ 
            int j =1;
            System.out.println(j);
          }
	}
}

This program give an error "variable j is already defined in method main"

See the code in C:

#include &lt;stdio.h&gt;

int main()
{
    int j = 0;
    while(j==0){ 
        int j =1;
        printf(&quot;%d&quot;,j);
    }
}

Here we get an infinite loop "11111111.............." As output.

Why does the C compiler not complain about the j variable as Java do?

答案1

得分: 3

为什么C语言编译器允许这种结构,而Java编译器不允许的直接答案是,这种结构在C语言中是合法的(在我使用的大多数词法作用域语言中也是合法的),但在Java中明确地不合法

我并不认为语言规范中的解释是有说服力的("仅使用简单名称无法区分已声明实体")- 嗯,是的,但这正是词法结构为您完成的。但尽管如此,这就是语言规定。

从积极的一面来看,意外遮蔽标识符是Java中不存在的错误源。

英文:

The straightforward answer of why a C compiler permits that construction, but a Java compiler does not, is that the construction is legal in C (and in most lexically-scoped languages that I've used), but is expressly not legal in Java.

I do not find the rationale in the language specification to be compelling ("it would be impossible to distinguish between the declared entities using only simple names") - well, yeah, but that's what the lexical structure is doing for you. But nevertheless, that's how the language is.

On the positive side, accidental obscuring of identifiers is a source of errors that cannot exist in Java.

答案2

得分: 0

只是因为C编译器只会向您发出警告,而不是错误...
你所做的并没有"错误",但是Java仍然会停止编译,因为在同一个函数内部调用具有相同名称的变量是一个非常不好的做法,而且很可能不是有意为之。
如果您在while()范围内更改了j变量的值,外部的j不会受到这些变化的影响。

英文:

Simply because C compiler would only launch a warning to you instead of an error...
What you did is not "wrong", but Java still stop compiling because calling a variable with the same name within the same function is a very bad practice and most probably not intentional.
If you change the value of j variable in the while() scope, the outside j will not be affected by the changes.

huangapple
  • 本文由 发表于 2020年10月3日 22:11:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64185147.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定