I'm not sure if I'm being really really stupid, but why doesn't this work?
void setup() {
Serial.begin(9600);
}
void loop() {
for (int x; x < 8; x++) {
for (int y; y < 8; y++) {
Serial.print(x);
Serial.println(y);
delay(100);
}
}
}
When this does:
void setup() {
Serial.begin(9600);
}
void loop() {
for (int x; x < 8; x++) {
Serial.println(x);
delay(100);
}
}
The first produces no output over Serial, whereas the second one prints out the numbers 0 to 7 as expected. I'm using a Teensy 3.1.
1 Answer 1
You are not initializing x and y.
When a local variable isn't initialized, it will "inherit" the value contained in the register assigned to the variable by the compiler. The fact that your single loop example worked is pure luck - the assigned register happened to contain 0 at that point in execution.
Change your nested loop like this:
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Serial.print(x);
Serial.println(y);
delay(100);
}
}
And it will work.
Note: Global variables, on the other hand, are guaranteed by the c++ standard to be initialized to zero. The compiler will make sure to write zeros to those memory addresses before the main program code executes.
-
I've spent too long writing Ruby...Alfo– Alfo2014年08月12日 16:02:34 +00:00Commented Aug 12, 2014 at 16:02
int x = 0;
insidefor()
statements (same fory
by the way)...