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.

Unexpected behaviour of unsigned int16 on underflow

Hello,

There appears to be some inconsistent behaviour with an unsigned 16-bit integer on underflow with optimisation levels 2 and 3.

I am compiling the following code in CCS v6.1.3 for Generic C64xx with compiler version 7.1.16 (problem also occurs with 6.1.21). Compiler flags: -mv6400 --abi=coffabi -O2 -g --include_path="/home/user1/ti/ccsv6/tools/compiler/c6000_7.4.16/include" --display_error_number --diag_warning=225

#include <stdio.h>
#include <stdint.h>

uint16_t var1;
uint16_t var2;
uint16_t msb_ext;
uint16_t set_high_if_msb_not_zero;

void check_underflow()
{
   var2 = var2 - 0x0002; // expect this to give 0xFFFF due to wrapping
   uint16_t msb = (var2 ^ var1) & 0x8000; // expect this to give 0x0000

   msb_ext = msb;

   if (msb != 0)
   {
      set_high_if_msb_not_zero = 1;
      var2 = var2 + 1;
   }
}

int main()
{
   msb_ext = 1;
   set_high_if_msb_not_zero = 0;
   var1 = 0x8000;
   var2 = 0x0001;

   check_underflow();

   printf("msb_ext: %u\n", msb_ext);
   printf("set_high_if_msb_not_zero: %u\n", set_high_if_msb_not_zero);
}

The console output is:

msb_ext: 0
set_high_if_msb_not_zero: 1

Examining the assembly, it appears that the value of msb used to write to msb_ext has the upper 16 bits zeroed (using EXTU) while the value used in the conditional has not. I know that behaviour of signed integers on overflow is undefined in the C99 standard but I thought that behaviour of unsigned integers was.

Thanks,

Bruce