-3

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 <stdio.h>

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

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

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

Jithin M V
  • 175
  • 1
  • 1
  • 10
  • @TonyTannous `C doesn't even know about your variable names` ? if the compiler does not know the variables name how it can produce code ? – bruno Oct 03 '20 at 14:15
  • The only relevant matter here is the language definition: is it legal to declare a variable in an inner scope that masks the variable in an outer scope. Different languages have different rules. It is nothing to do with "metadata". – J.Backus Oct 03 '20 at 14:37

2 Answers2

3

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.

J.Backus
  • 1,441
  • 1
  • 6
  • 6
0

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.