2

I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?

5
  • 5
    Use unsigned integers. If you need a specific size, use uint8_t, uint16_t, uint32_t or uint64_t. They are respectively 8, 16, 32 and 64 bits wide. Commented Nov 9, 2016 at 20:30
  • 1
    For reference, all integer types can be incremented and will overflow with predictable behavior. What kind of weird overflow issues were you getting with ints? What are you trying to do?
    – mwwalk
    Commented Nov 10, 2016 at 3:02
  • 1
    @mwwalk: What you say is absolutely wrong! Please, do not spread such nonsense over the Internet. Signed integer overflow is undefined behavior in C and C++. In some sense, it is considered “illegal”. Technically, it means the compiler will assume your signed integers do not overflow, and optimize your code on the basis of this premise, completely disregarding the possible consequences of the premise possibly being wrong. Then, any kind of weird behavior can happen if you overflow a signed integer. Unsigned integers, on the other hand, have predictable overflow behavior. Commented Nov 10, 2016 at 8:44
  • 1
    @mwwalk: Here is a good read about undefined behavior in C and C++, with some enlightening examples related to signed integer overflow (see part 2): A Guide to Undefined Behavior in C and C++. Commented Nov 10, 2016 at 9:46
  • Yeh, I take it back and I was obviously wrong. But you could calm down a little, I obviously didn't mean to be wrong and I'm not trying to push some alternative overflow agenda. I just made a mistake. Literally every time I've ever had an integer overflow, it has done so in the predictable and expected manner. Apparently I've just gotten lucky so far.
    – mwwalk
    Commented Nov 11, 2016 at 4:15

1 Answer 1

1

Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.

https://forum.arduino.cc/index.php?topic=85692.0

a library by Nick Gammon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.