3

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?

9
  • how are you getting the output? Commented Apr 29, 2015 at 15:18
  • 1
    do you mean to say a==0, b==1, c==2, d==3 ? Commented Apr 29, 2015 at 15:19
  • There shouldn't be a problem with doing this but a will end up being 3 not 0, since you are still incrementing it. Also b will start at 0 since you are effectively assigning then incrementing. But I don't see why you would need to, if you're giving a variable initial data you obviously know the initial data you want! ^^ Commented Apr 29, 2015 at 15:20
  • Perhaps the developer will later want to change the original value. Commented Apr 29, 2015 at 15:20
  • But in that case it would still be just as easy to type out the new values (providing all he wanted to do was still increment) Commented Apr 29, 2015 at 15:21

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.