well this is driving me nuts....
I have a for loop with a condition that has two parts connected with logical AND &&
for (int i = 1 ; ((i <= MAX_CHANNELS) && (rslights[i].type != 'W')) ; ++i)
as I understand it, if the condition is false, the loop body will not execute.
Since both parts are connected with &&, both parts must be true for the overall condition to be true.
Since one part is a counter, and i is not altered in the body or the other condition, this loop should never iterate more than MAX_CHANNELS which is 5.
What happens though is that the loop iterates way more than 5 - usually until reading of memory gets nasty and an exception is thrown.
In my mind, at most, 5 iterations should happen, no matter what (rslights[ i ].type != 'W') evaluates to. If I alter the condition to compare it with data that is in the array, the loop works. in other words, once it evaluates as true, it seems to affect the left hand condition as if the two were connected with logical OR ||
I am certain I don't need an OR, it has to be an AND, as I want the loop to end if either condition is false.
Now, the condition does involve a variable that is a struct. If is use a plain char variable it works as expected.
I am able to access rslights[ i ].type within the body and results are as expected. Do members of a struct have to have some special way of referencing them in a logical condition?
Here is a sample sketch demonstrating the issue...
#include "ESP8266WiFi.h"
const int MAX_CHANNELS = 5; // size of rslights array
struct RSLight {
// design time values
char type; // L = monochrome light
int pin; // raw pin number
};
RSLight rslights[MAX_CHANNELS];
void sendCHdata() {
Serial.println(MAX_CHANNELS);
for (int i = 1 ; ((i <= MAX_CHANNELS) && (rslights[i].type != 'W')) ; ++i) {
Serial.println(rslights[i].type);
Serial.println(i);
}
}
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("setup");
rslights[1].type = 'X' ;
rslights[2].type = 'Y' ;
rslights[3].type = 'Z' ;
rslights[4].type = 'P' ;
rslights[5].type = 'Q' ;
sendCHdata();
}
void loop() {
}
and some of the Serial output (which ran until i == 2952 and crashed.)
setup
5
X
1
Y
2
Z
3
P
4
Q
5
⸮
6