Is it risky to initialize a global variable with an increment of another global variable?
Example:
int a=0;
int b=a++;
int c=a++;
int d=a++;
This should output:
0,1,2,3
Could it happen that compiler could read a global value before the other?
It will behave as expected. If you try to use a field before it's defined, the compiler will throw an error:
public class Foo {
int a = b++; //compiler error here
int b = 0;
}
This is covered in JLS 8.3
For your case, the output of the variables if they're not modified, would be:
a = 3
b = 0
c = 1
d = 2
Result will be a=3, b=0, c=1, d=2.
If all this variable declared in one class they will be initialized in order of occurrence in code.
PS: b = 0 because a++ get value and then increment variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With