For loop and break

I'm having some issues (I think) with a for loop, and break().

I read in the documentation this example:

int threshold = 40;
for (int x = 0; x < 255; x++) {
  analogWrite(PWMpin, x);
  sens = analogRead(sensorPin);
  if (sens > threshold) {     // bail out on sensor detect
    x = 0;
    break;
  }
  delay(50);
}

Looks okay, but why is that line
x=0;
in there?
It's going back to zero next time the for loop is entered isn't it?

Thanks

It is not required. The next time through the for loop x is initialised to 0.

If you set to 255 instead, then the break would not be required.

1 Like

This line is doing nothing and can be removed, because the break in the next line breaks loop anyway.

When loop entered next time, X will be assigned to zero in the for statement, regardless previous break.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.