I am trying to understand why I get different results from this demo sketch when I make changes like making the variable "y" global, or replacing "if (x > 3)" with "if (1)".
First, defining "y" within loop().
int x = 6;
void setup() {
Serial.begin(9600);
delay(500);
}
void loop() {
int y; // <------------
prt('A', x, y); // A 6 0
if (x > 3) {
prt('B', x, y); // B 6 0
}
else {
prt('C', x, y); // nothing printed here
if (1) y = 1; // how can y become 1 here ?
prt('D', x, y); // nothing printed here
}
prt('E', x, y); // E 6 1 (y not expected)
while (1);
}
void prt(char i, int x, int y) {
Serial.print(i);
Serial.print("\t");
Serial.print(x);
Serial.print("\t");
Serial.println(y);
}
Then with "y" as a global variable.
int x = 6;
int y; // <------------
void setup() {
Serial.begin(9600);
delay(500);
}
void loop() {
prt('A', x, y); // A 6 0
if (x > 3) {
prt('B', x, y); // B 6 0
}
else {
prt('C', x, y); // nothing printed here
if (1) y = 1;
prt('D', x, y); // nothing printed here
}
prt('E', x, y); // E 6 0 (y expected)
while (1);
}
void prt(char i, int x, int y) {
Serial.print(i);
Serial.print("\t");
Serial.print(x);
Serial.print("\t");
Serial.println(y);
}
And then "y" defined within loop() again, but now with "if (x > 3)" replaced with "if (1)".
int x = 6;
void setup() {
Serial.begin(9600);
delay(500);
}
void loop() {
int y; // <------------
prt('A', x, y); // A 6 0
if (1) { // <------------
prt('B', x, y); // B 6 0
}
else {
prt('C', x, y); // nothing printed here
if (1) y = 1;
prt('D', x, y); // nothing printed here
}
prt('E', x, y); // E 6 0 (y expected)
while (1);
}
void prt(char i, int x, int y) {
Serial.print(i);
Serial.print("\t");
Serial.print(x);
Serial.print("\t");
Serial.println(y);
}
How can "y" become 1 in the first example ?
How can this be cured by any of the two changes ?
I am asking because if I do not understand why this is happening in a small test sketch, then I may get into real trouble further down the road.
IDE 1.8.16, same result with different MCUs.