Problem in the for loop

Hello,

This piece of code runs fine:

 for(int i = 7500; i < 12500; i+=5)
   {
     Serial.print("i = "); Serial.println(i);
     delay(500);
    }

if I change 7500 into 75000 and 12500 into 125000, the for-loop starts at 9464 and not at 75000. Anyone knows what is wrong?

Osiris

Welcome to the forum

Check carefully the range of values that an int can hold, particularly as it is a signed data type so can go negative

Review how big a number fits in an int.

Change your variable type to long.

a7

1 Like

Changing the int into a long fixed the problem.
Thank you very much!

Osiris

Did you understood the issue?

Yes I understand the issue (now). An Integer on arduino Uno is 16 bytes. MSB is the signed bit so that leaves : 15 bits(-1) = (2^15) - 1 = 32,767.
The number 75000 is to big for a 2 byte Integer and thus overflows twice:
75000 - 32,767 - 32,767 = 9466.

I also write software on a teensy 4.1 where an integer is 4 bytes. I forgot about the size of an integer on an arduino Uno.

Osiris

3 Likes

16 bits :wink:

1 Like

Thank you for correcting me. We have to stay correct. :slight_smile:

Osiris

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