0

I am just starting to experiment with for-loops, and noticed that whether I declare the integer used as i in the for-loop as a global or local variable, it's value seems to be reset each time the following function is run:

function inccountNum() public {
for(i = 0; i < 4; i++) {
    countnum += 2; 
}

In other words, I declared i as a global variable, and expected it to be equal to 4 at after executing this function and for countnum (another global variable), to be equal to 8. This in fact was the case.

However, I expected that running the function again would not be possible, since the variable i = 4 and so can not be < 4. Instead, I see that i still equals 4 and now countnum = 16.

I even tried setting the global i to 25, assuming the function wouldn't run at all, but it still worked and i was again equal to 4.

Is it safe to assume that the "i = 0" part of the for-loop resets the value of i to zero each time the function is run?

1

Yes. That loop could logically be written like this:

i = 0;
while (i < 4) {
    countnum += 2;
    i++;
}

Which means that i is being set to 0 every time the for loop is run.

If you do not want to initalize the variable, and only have the loop run while your global variable is less than 4, then you can simply use the while loop I posted above instead, without the initialization:

function inccountNum() public {
  while (i < 4) {
    countnum += 2;
    i++;
  }
}

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.