in my project I discovered some weird behaviour regarding comparison operators. So I took the code apart, trying to find the error but I still cant figure out whats going on.
I expect boolVar to become 0 (false) once i becomes bigger than x. But it doesn't.
The problem disappeares when I change x=10 to x=5 or tmpArray[ i ] to tmpArray[ 2 ].
Whats going on here?
Code:
int x = 10; //Output is correct when I change this to x=5
int tmpArray[10] = {1,1,1,1,1,1,1,1,1,1};
void setup()
{
Serial.begin(9600);
}
void loop()
{
int i=0;
while( tmpArray[i] != 0 ) //Output is correct when I change this to tmpArray[2]
{
Serial.print("i=");
Serial.print(i);
Serial.print(" x=");
Serial.print(x);
bool boolVar = (i < x);
Serial.print(" (i < x)=");
Serial.println(boolVar);
delay(50);
i++;
}
}
Output:
i=0 x=10 (i < x)=1
i=1 x=10 (i < x)=1
i=2 x=10 (i < x)=1
i=3 x=10 (i < x)=1
i=4 x=10 (i < x)=1
i=5 x=10 (i < x)=1
i=6 x=10 (i < x)=1
i=7 x=10 (i < x)=1
i=8 x=10 (i < x)=1
i=9 x=10 (i < x)=1
i=10 x=10 (i < x)=1
i=11 x=10 (i < x)=1
i=12 x=10 (i < x)=1
Looks like a case of undefined behavior. It's never valid to access tmpArray past index 9, so the compiler appears to use that knowledge to always set boolVar to true (instead of comparing i with x). The compiler figures that if i becomes greater than 9, who cares what the results of the program are? You're doing something undefined so the results in those cases don't matter. Yes, the compiler really is free to optimize like that, and yes, it sometimes does so.