Order of Commands

Folks,

Trying out some very simple code to familiarise myself with FOR control I entered the following - this worked fine;

void loop()    {
for (int number = 2; number <=20; number ++)
Serial.println(number);
delay(5000);
}

Purely for practice purposes I entered similar (just variable different name) and kept getting errors - one being ‘value’ not declared in this scope. Code as follows;

void loop()    {
for (int value = 0; value <= 15; value ++)

delay(1000);
Serial.println(value);
// delay(1000);

}

I was going mad trying to resolve this then realised I had Serial.println(value) and delay(1000) in a different order.

I am struggling to understand why this makes any difference at all and would appreciate if someone could throw some logic on this.

Geoff

When you write a for loop without braces, only the first statement following the for statement will be looped. By moving Serial.println(value); after delay(1000);, you moved Serial.println(value); out of the scope of the for loop. The value variable only had scope within the for loop.

This sort of thing is very common. That is why I strongly recommend that you always use braces. Even if you only have a single statement now, you might add another one in later. The tiny amount of time you would have saved not having to type two characters will be lost many times over on the first bug it causes.

The other thing you should do is to always do a Tools > Auto Format on your code. Its automatic indentation makes it clear what’s happening. Here’s how your code would have looked if you had auto formatted it:

void loop()    {
  for (int value = 0; value <= 15; value ++)

    delay(1000);
  Serial.println(value);
  // delay(1000);

}

You can clearly see that only the delay statement is in the for loop scope.

Thank you for explanation.

Been out of programming for some years but slowly getting an understanding.

Your reply very helpful.

Geoff