'comparison is always true due to limited range of data type' warning in C?

陌路散爱 提交于 2019-12-01 03:39:17

问题


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.


回答1:


Are you sure that char is signed? Try declaring the fields explictly as signed char and see what you get.




回答2:


I guess x >= 0 causes the warning because char might be implemented as unsigned char.




回答3:


The char type may be signed or unsigned. It depends on your compiler vendor's choice. There might even be a compiler option available. Evidently, char is unsigned for you, so it's always greater than or equal to zero, and thus the compiler warns you.

You're using char here to represent "a numeric type that takes up minimal memory." In that case, I recommend explicitly using signed char or unsigned char. (Each is distinct from plain char, despite char having to be either signed or unsigned.) Reserve char for when you're holding character data. For numeric data, use one of the other two types.




回答4:


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




回答5:


The C and C++ standards allows the character type char to be signed or unsigned, depending on the platform and compiler. Most systems, including x86 GNU/Linux and Microsoft Windows, use signed char, but those based on PowerPC and ARM processors typically use unsigned char.(29) This can lead to unexpected results when porting programs between platforms which have different defaults for the type of char.




回答6:


Try this:

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


来源:https://stackoverflow.com/questions/757482/comparison-is-always-true-due-to-limited-range-of-data-type-warning-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!