Search code examples
cembeddedxc8

mismatched comparison in XC8


Mismatched comparsion when a definition EUSART_BUFFER_SIZE is compared with a variable eusart_rx_buffer_rd of type uint8_t. But if the type of the variable is changed to uint16_t the warning is gone. Why?

#define EUSART_BUFFER_SIZE 256
uint8_t eusart_rx_buffer_rd = 0;            

if (eusart_rx_buffer_rd >= EUSART_BUFFER_SIZE)                 
 {
     eusart_rx_buffer_rd = 0;
 }

Solution

  • The implicit type of the literal constant 256 is int, so you are comparing an int with a uint8_t.

    The comparison itself causes an implicit promotion to int, but is in any case always false since 256 is not representable by a uint8_t.

    It is not clear what the appropriate solution might be, but if all values of the uint8_t variable are valid, the test serves no purpose, and a naive change to a larger type may in fact introduce bugs by allowing invalid values to be assigned.