0

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.

asked Aug 10, 2014 at 14:18
3
  • Very odd... doesn't work for me on Mega 2560. I must be missing something obvious :-) Commented Aug 10, 2014 at 14:26
  • yes, obvious: int x = 0; inside for() statements (same for y by the way)... Commented Aug 10, 2014 at 15:32
  • !enter image description here How we can solve question 18 ? Commented Oct 24, 2018 at 20:45

1 Answer 1

7

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.

answered Aug 10, 2014 at 15:43
1
  • I've spent too long writing Ruby... Commented Aug 12, 2014 at 16:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.