Bookmark Topic Watch Topic
  • New Topic

Initialization a variable before declaration

 
Sanjit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Report post to moderator
hi everyone,

please help me to clear the following doubt.

1>what is the rule to use a variable(read or write) before declaration.

2> code snippet:
class MyClass{

static{
int x = 2 * var1; //line1
int y = 3 * MyClass.var1; //line2
}

static{
int var1 = 10;
}

In the above code line1 gives error but line2 runs successfully.I am not able to understand the behaviour. Please explain how this code is working.

How the compiler(or system) handles or process var1 in line2 which is running nicely without declaring var1 before using it at line2.

I hope i am very much clear what i am trying to ask....if not please reply back..
Thanks in advance
 
Henry Wong
author
Marshal
Pie
Posts: 21024
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
First, please read this. This explains why it is important to not crosspost, and to choose the correct forum.

This forum is for the discussion of Errata. In order to do that, we need to know which mock this question is from, and why do you think it is wrong. In any case, the other copy of this topic is probably in the correct forum, so I'm locking this one.

Henry
 
    Bookmark Topic Watch Topic
  • New Topic