Thiago R. Adams website

Home Code-Blog Projects Twitter Blog Links / Books About

Websites

Useful functions to avoid underflow/overflow and using the remaining value.


unsigned int UnsignedSubtraction(unsigned int a, unsigned int b,
unsigned int* r)
{
   const unsigned int minval = 1;
   const unsigned int avaiable =  a - minval;
   if (b > avaiable)
   {
      *r = b - avaiable;
      return minval;
   }

   *r = 0;
   return a - b;
}


unsigned int UnsignedAddition(unsigned int a, unsigned int b, unsigned int* r)
{
   const unsigned int maxval = 255;
   const unsigned int avaiable = maxval - a;
   if (b > avaiable)
   {
       *r = b - avaiable;
       return maxval;
   }

   *r = 0;
   return a + b;
}

Want to see more? Go to the CodeBlog section.

About the author: I am Thiago Adams. I work as a professional C++ software engineer. I have created this website to share ideas and source code with other people with similar interests.
I would like to hear from you comments, critics, questions and suggestions about this topic or any other part of this website. Email: thiago.adams at gmail dot com