Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to silence a particular "pointless comparison of unsigned with zero" warning?

Tags:

c

warnings

Suppose I have a function like the following:

#define LOWER_BOUND 0
#define UPPER_BOUND 42

int is_value_in_range( some_typedef val)
{
    return ((LOWER_BOUND <= val) && (val <= UPPER_BOUND));
}

Assuming that I have warnings configured appropriately, if some_typedef turns out to be an unsigned type I'll get a warning that there's a pointless comparison of an unsigned type with 0. Of course that's true, and it makes sense.

However, lets say that I do want the check against zero to be in the code for one or more possible reasons, such as:

  • While the bounds will always be compile time constants, they might be something that could change (and the macros might not 'live' very close to the function). For example, the bounds might be set by passing in options to the compiler.
  • I might like to defend against a later change of the typedef to a signed type, since it's possible that each and every use of the typedef might not be closely examined when it's changed.

Is there a decent, reasonably portable way to silence the warning here without turning it off completely?

Something that relies on a 'STATIC_ASSERT()'-like functionality (which is available to me) would be acceptable if it's reasonable. I'm OK with breaking the compile if the type changes to force someone to look at the code. But it might be important to note that typeof isn't something I have available in all the compilers I'm targeting.

I'm specifically looking for C language solutions, so templates aren't any use here...

like image 875
Michael Burr Avatar asked Jun 06 '11 23:06

Michael Burr


2 Answers

If some_typedef is not known to be unsigned or signed, I think you're pretty much out of luck.

If you know in advance that some_typedef is unsigned, you could just use

#if LOWER_BOUND > 0
    return ((LOWER_BOUND <= val) && (val <= UPPER_BOUND));
#else
    return ((val <= UPPER_BOUND));
#endif

Or in this case, you could use my preferred version:

    return (val-LOWER_BOUND <= UPPER_BOUND-LOWER_BOUND);

Edit: I'm going to assume if some_typedef is not known to be of particular signedness, then UPPER_BOUND and LOWER_BOUND must both be positive. Otherwise you would have very wacky results from some_typedef getting promoted to unsigned. Thus, you could always safely use:

    return ((uintmax_t)val-LOWER_BOUND <= UPPER_BOUND-LOWER_BOUND);
like image 143
R.. GitHub STOP HELPING ICE Avatar answered Sep 22 '22 10:09

R.. GitHub STOP HELPING ICE


That's usually controlled by pragmas. For MSVC, you have #pragma warning and for GCC you have diagnostic pragmas (which admittedly don't allow for as fine-grained control over warnings as MSVC, but that's all you have).

Both allow for push/pop mechanics to only change the warnings for a few lines of code.

like image 29
Blindy Avatar answered Sep 23 '22 10:09

Blindy