This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Overflow with signed and unsigned integers

Hello,

            Is there any procedure to limit the math from overflow & underflow conditions built in CCS?

  • Harika Rao Vamulapalli said:
    Is there any procedure to limit the math from overflow & underflow conditions built in CCS?

    You want a latchup of the result? That's not part of the C language. Variabels roll over when exceeding their value range.

    What you can do is a 'software latchup'. Do the math on a larger range (e.g. by casting oen of the INT parameters to LONG INT). Then on the result make a >>16. If it is zero, there was no rollover, if is is !=0, there was.

  • In case of addition and subtraction you can also split up your calculation and check the overflow flag after each step (you have to get the SR for that) - which gets quite ugly, so it should be put into a method. Still looks ugly and is probably quite slow, but I needed this as well in my code.

    For multiplication you can use the saturation mode of the MPY if you have that available - otherwise I'm not sure if the overflow flag can be used in that case, probably not. 

  • Bernhard Weller said:
    In case of addition and subtraction you can also split up your calculation and check the overflow flag after each step (you have to get the SR for that)

    This is only possible in assembly language. The C language does not 'know' of things like th eoverflow bit. And there is no guarantee that these status bits haven't changed even if you use one of the intrinsics to retrieve the status register.
    The compiler may even have reordered your code so that the status regsiter contains the status from a completely different operation.
    In C, the only reliable way to detect an overflow is to do the operation in a larger data range and check the upper (overflowing) part of the result. Everythng else may break with the next ompielr version or even with the same compiler version but different project settings.

**Attention** This is a public forum