Take the 2-minute tour ×
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

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.

share|improve this question
    
Very odd... doesn't work for me on Mega 2560. I must be missing something obvious :-) –  Annonomus 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

1 Answer 1

up vote 7 down vote accepted

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.

share|improve this answer
    
I've spent too long writing Ruby... –  Alfo Aug 12 '14 at 16:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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