Note to self – subtracting unsigned integers

I was having a small Arduino problem this weekend involving counters so had to do some research on subtracting unsigned integers from one another in the context of counter rollover. Interesting solution to that problem using modulus UINT_MAX+1. Thank you to this answer on Stackoverflow.com (Is unsigned integer subtraction defined behavior?). Below is my test code.

#include <stdio.h>

unsigned char counter = 0;
unsigned char previousCounter = 0;
unsigned int interval=47;

int main () {
   for (int x=0; x= interval) { // check for rollover
         printf("Reached interval at %d (%d), %d n",
            currentCounter, previousCounter, (unsigned char)(currentCounter - previousCounter));
         previousCounter = currentCounter;
      }
   }
}

Published by

lekkim

Positive, competent, out-spoken, frank and customer focused architect and developer with a strong foundation in web, cloud and product development. I'm a strong advocate for API first and cloud based solutions and development. I have a knack for being able to communicate and present technically complicated matters in conference, customer and training settings. I've previously acted as team member and leader in a product organisation.