"Comparison is always true due to a limited range of data types" in C?

I have the following code

//Point.h
#define WIDTH 8
#define HEIGHT 8

typedef struct Point
{
  char x;
  char y;
} Point;

//Board.c
#include <stdbool.h>

// Some other functions that we don't care about... 

bool inBounds(Point * p)
{
  return p->x >= 0
    && p->x <= WIDTH
    && p->y >= 0
    && p->y <= HEIGHT;
}

When I compile this (ppu-gcc 4.1.1), I get the following warning

warning: comparison is always true due to limited range of data type

although the char range is from -127 to 127, and the WIDTH is 8, which is within the char range. I already tried explicit conversion of WIDTH to char, but still got an error.

+5
source share
6 answers

Are you sure you are signed char? Try explicitly declaring the fields as signed charand see what you get.

+14
source

, x >= 0 , char unsigned char.

+3

char . . , . , char , , , , .

char " , ". signed char unsigned char. ( char, , char .) char, . .

+3

Hummm... char ? 0-255, , s >= 0 .

+1

C and C ++ standards allow you to sign a char character type with or without an unsigned character, depending on the platform and compiler. Most systems, including x86 GNU / Linux and Microsoft Windows, use signed char, but PowerPC and ARM processors usually use unsigned char. (29) This can lead to unexpected results when transferring programs between platforms, the default values ​​for the type char.

0
source

Try the following:

typedef struct Point
{
  signed char x;
  signed char y;
} Point;
0
source

All Articles