When developing an Android app in Android Studio, a variable used within a while loop has an incorrect value. I reduced it in a test case to a very simple case:
- Create a new project in Android Studio, blank Activity
- Add the following code to the main activity
method onStart:
@Override
public void onStart() {
super.onStart();
int count = 2;
int index = 1;
int value = 23;
Log.i("test", "value before = " + value);
while (index < count) {
Log.i("test", "value in while loop = " + value);
index++;
value = 0;
}
}
The output when executing the test app is:
value before = 23
value in while loop = 0
while the result should be
value in while loop = 23
When debugging, the result is as expected ('value in while loop = 23'), but in a regular debug build, it is wrong. The disassembled code of the main activity class looks ok, the value of the variable 'value' is set to 0 at the end of the while loop body. When some code or a function within the while loop body uses the variable 'value' it will have the value 0 instead of 23. In the test case I use the Log statement to simplify.
It doesn't go wrong when I change the line
value = 0;
to
if (value == 23) {
value = 0;
}
or when I remove the line
value = 0;
So it looks like some optimization error. But what optimization is done that could cause this? It makes the code unreliable.