Compaison Operator doesnt work as expected

Hello,

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

Delta_G:
I notice right off the bat that you're reading off the end of your array once i gets to 10 or more.

Yes, I know that. This is not the code I actually use. Its just a stripped down version where I try to find the mistake.

Yes, I do go beyond the borders of the array, but why would the comparison (i < x) be affected by that. The array is not involved here.

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.

Okay, thank you both for your help and the code examples, I think I got it now!

As soon as the program realizes "Whoops, I am going out of bounds here!" it stops working correctly and does whatever it wants to do.

Which is also the reason why with this code it wont stop:

while( (tmpArray[i] != 0) && (i < 10) )

But with this it does:

while( (i < 10) && (tmpArray[i] != 0))

As soon as I access data outside of my array, I can't rely on proper results anymore.
Thank you :slight_smile: