What are all num referring to ?

class Sample {
  int num;

  void method() {
    num = 1;
    int num = num = 2;
    num = 3;
  }
}

Recommended Answers

All 5 Replies

If I compiled this with say GCC and the usual optimizer settings those lines 5, 6 and 7 would vanish along with method so the variable num would never exist at runtime. So there is no num so there is nothing being referred to in this example.

class Sample {
  int num;
  void method() {
    num = 1; // Sample.num is set to 1
    int num = num = 2; // num in method is set to 2, the second num is num in method
    num = 3; // num in method is set to 3
  }
}

I tried the code in https://www.tutorialspoint.com/compile_cpp_online.php

class Sample {
  public:
    int num;
  int method() {
    num = 1;
    int num = num = 2;
    num = 3;
    return num;
  }
};
Sample s;
cout << s.num << endl; 
cout << s.method() << endl;
cout << s.num << endl; 

Output:
0
3
1

but your tag is Java, so it should be interpreted as Java code. I will try it in Java.

commented: Nice work but you added code so my observation won't apply since you changed the code. +15

Now in Java:

class Sample {
      public int num;
      public int method() {
        num = 1;
        int num = num = 2; // in Java: second num seems to be public num
        num = 3;
        return num;  
      }
    }
   Sample s = new Sample();
   System.out.println(s.num);
   System.out.println(s.method());
   System.out.println(s.num);

Output:
0
3
2
So, the output is different to C++.

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears (Java Language Spec 6.3)

So the exibited behaviour is what the JLS requires, depending on how you see the multiple assignment, but 4.12.3 seems to clarify that

a local variable could always be regarded as being created when its local variable declaration statement is executed.

because the declaration/intialisation will be executed after the assignment to its right.

Thanks guys for the explanation

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.