Search code examples
cgcc-warning

GCC warning 'comparison is always true' when comparing the return of ntohs with a integer


I'm having a hard time to understand why I'm getting this compilation warning while using GCC 4.8.4 on Linux:

warning: comparison is always true due to limited range of data type [-Wtype-limits]

when comparing values like these:

uint16_t port_number = 23620;

if (ntohs(port_number) >= 0 && ntohs(port_number) <= 1023) {
    puts("The compiler warns that I will always end up here.");
} else {
    puts("Not reached");
}

I understand that the problem is due to the max size supported by each value involved in this comparison. But how can I understand this better and fix it?


Solution

  • ntohs returns a uint16_t. Since uint16_t is unsigned, it will always be greater than or equal to 0. Therefore, ntohs(port_number) >= 0 will always resolve to true. This is why you're getting the warning.