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.

  • Very odd... doesn't work for me on Mega 2560. I must be missing something obvious :-) – Anonymous Penguin Aug 10 '14 at 14:26
  • yes, obvious: int x = 0; inside for() statements (same for y by the way)... – jfpoilpret Aug 10 '14 at 15:32
  • !enter image description here How we can solve question 18 ? – Shamma Oct 24 '18 at 20:45
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.

  • I've spent too long writing Ruby... – Alfo Aug 12 '14 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.