Kraken
Kraken

Reputation: 24233

Scoping rules for variables

Out of nowhere, I started thinking about the scoping rules of variables. I am not new to programming, and that scares me even more that I do not know the answer to this question.

I remember reading about the variables scoping on the web, and they'll have this example where in they will have a variable declared outside a {}, and they'll change the value inside the {} block, and when they print it in these two different scopes, they get different results.

Now, in the below code.

main(){
  int a=20;
  sysout(a);

  if(true){
    a=30;
    sysout(a);
  }
  sysout(a);
}

now, I get 20,30,30 as output. and I am ok with this. But then I am thinking what were those examples on the internet that showed me different results. So I thought I'll declare a again inside the {}

Code:

main(){
  int a=20;
  sysout(a);

  if(true){
    int a;  // In java, this gives me error, saying duplicate local variable a.
    a=30;
    sysout(a);
  }
  sysout(a);
}

So, what exactly was that example that I saw on the net. If someone can put me out of my misery.

Thanks

Upvotes: 1

Views: 65

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172608

Local variables cannot be redeclared in the local scope. In the second case, your variable a is in the local scope of main method and you are again trying to declare it in the local scope of if block which is not allowed.

You may better try this:

int a=20;   //Here a is outside the scope of main, so you can redeclare it.
main(){
  sysout(a);

  if(true){
    int a;  
    a=30;
    sysout(a);
  }
  sysout(a);
}

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

Should this be the example:

int a=20;
main(){
  sysout(a);

  if(true){
    int a = 30;  // now this will shadow the class variable a
    sysout(a);
  }
  sysout(a);
}

Now output should be:

20 30 20

Upvotes: 3

Related Questions