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
even though the range of char is -127 to 127 and WIDTH is 8, which is well inside the range of a char. I've already tried an explicit cast of WIDTH to a char, but still got the error.
-
Are you sure that
charis signed? Try declaring the fields explictly assigned charand see what you get.Wedge : Yeah, I believe char is unsigned, so it's the comparison to 0 that will always be true.Dan Breslau : It's compiler-dependent. If you *need* char to be signed, you need to declare it as signed.Paul Wicks : Yeah this, fixes it. However, the lines that I was getting an error on were the lines where I was making a comparison against positive numbers (the WIDTH and HEIGHT). Strange.Dan Breslau : The compiler must be using 0-based line numbers :-) Actually, you may have a different problem there: Using <= and >= means that you have an effective WIDTH and HEIGHT range of 9, not 8. If that's what you want, perhaps you should use different macro names (MAX_X and MAX_Y?) -
Hummm... isn't your char unsigned by default? In that case the range would be 0-255, which means your >=0 comparison would be always true
ephemient : It's platform- and compiler-dependent. For example, GCC on x86 Linux uses signed char by default, while GCC on PowerPC Linux uses unsigned char by default. -
I guess
x >= 0causes the warning becausecharmight be implemented asunsigned char. -
The
chartype may be signed or unsigned. It depends on your compiler vendor's choice. There might even be a compiler option available. Evidently,charis unsigned for you, so it's always greater than or equal to zero, and thus the compiler warns you.You're using
charhere to represent "a numeric type that takes up minimal memory." In that case, I recommend explicitly usingsigned charorunsigned char. (Each is distinct from plainchar, despitecharhaving to be either signed or unsigned.) Reservecharfor when you're holding character data. For numeric data, use one of the other two types.dfa : this is confirmed by: http://www.network-theory.co.uk/docs/gccintro/gccintro_71.html
0 comments:
Post a Comment