Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: comparison is always false due to limited range of data type in gcc 4.1.2

Tags:

c

linux

gcc

I encountered the following warning from gcc 4.1.2:

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

the concerned C code is like:

if ( unlikely(count < 0) ) BUG();

where 'count' is unsigned.

I tried to disable the warning since I was not allowed to modify the source code:

-Wno-type-limits

but it seems gcc 4.1.2 does not support it.

cc1: error: unrecognized command line option "-Wno-type-limits"

Any other ways to get rid of this warning?

like image 563
user1783732 Avatar asked Mar 14 '13 00:03

user1783732


3 Answers

An unsigned value will never be negative — hence the warning. It's not so much 'unlikely' as 'impossible'.

This usually indicates that there is a bug in the code of some sort; the code was written expecting a type that could allow negative values, but the type doesn't allow negative values. So, it is quite possible that the code will misbehave because of the mismatch in expectations.

Note that on some machines, plain char is signed and on others unsigned (and it is a type distinct from both signed char and unsigned char even though its range of values overlaps with one or the other).

like image 75
Jonathan Leffler Avatar answered Nov 11 '22 12:11

Jonathan Leffler


options to fix this warning:

  1. remove condition which alway true

  2. best: remove condition which alway true + add static_assert to ensure type is unsigned. (for C version of static_assert look here)

  3. for gcc prior 4.3: remove compiler option: -Wextra

  4. for gcc 4.3+ add option: -Wno-type-limits

like image 33
Maxim Kholyavkin Avatar answered Nov 11 '22 13:11

Maxim Kholyavkin


Depending on how old the source code is, it could be written in a defensive manner for a time where compilers were not as type-safe as gcc is now.

The warning looks like it's part of the -Wextra (aka -W) warning option set, so if you want the extra warnings, that will be one of them. I personally use -Wall, which believe it or not does not include the "extra" stuff. You would think that "all" would include "extra" but I guess not...

like image 2
SeKa Avatar answered Nov 11 '22 13:11

SeKa