1

I would like to add x to y (where y is an attribute of class A)

void A::f1(char x)
{
  y += x;
}

However, there is a risk of overflow. I think (I have not tested them) the following two functions should prevent any overflow however they seem very uselessly complicated (and not very fast for the concern of f3).

void A::f2(char x)
{
    if (x > 0)
    {
        if (CHAR_MAX - x < y)
        {
            y = CHAR_MAX;
        } else if (CHAR_MIN + x > y)
        {
            y = CHAR_MIN;
        } else
        {
            y += x;
        }
    } else
    {
        if (CHAR_MAX + x < y)
        {
            y = CHAR_MAX;
        } else if (CHAR_MIN - x > y)
        {
            y = CHAR_MIN;
        } else
        {
            y += x;
        }
    }
}

void A::f3(char x)
{
    if (x < 0)
    {
        for (int i = 0 ; i < x;i++)
        {
            if (y == CHAR_MIN)
            {
                break;
            }
            y--;
        }    
    } else
    {
        for (int i = 0 ; i < x;i++)
        {
            if (y == CHAR_MAX)
            {
                break;
            }
            y++;
        }
    }
}

Is there a better solution?

Remi.b
  • 17,389
  • 28
  • 87
  • 168

0 Answers0