Counter goes negative after reaching break point

Hi! I've gotten stuck on this piece of code. I tried to add a screenshot of it (Idk if it worked, I haven't used this forum before).

Basically, in my loop:

if (counter < 5) { /* do something */}

The counter increments correctly to 4, but then switches to -32768 and keeps adding one. Therefore the if statement keeps executing even after 5 loops (Because negative number is less than 5).

I have tried changing the limit from 5 to a variety of different numbers and the behavior is the same every time.

Does anyone know why this behavior is happening and how I can get it to behave as intended?

Thank you!

Post the whole code. There is information in the missing part. Read the forum guidelines to see how to properly post code.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

Whiles waiting for the code, When the counter gets to 5, I take it that's a limit and the counter should be set back to 0?

The counter goes to 6 or 7 or 8 or keeps on counting till the variable overflows then that's a possible cause of this issue.

1 Like

The Serial.println can only happen when counter is less than 5. Once counter is 5 or greater nothing will print, but the counter still increments, until the counter (an int data type) rolls over at 32767 to -32768. Then -32768 is less than 5 so it starts printing again adding one each iteration (-32767, -32766, ...) until it gets to (+) 5 and stop printing again.

1 Like

If less than 5 then you print the count... but your code continues to add 1 to the counter every loop...

16 bit integers range from -32768 to +32767.

Eventually it gets to +32767... then you add one more.. and it overflows to -32768 (which is less than 5 so it displays again.

1 Like

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