7

I have some code like

Q_ASSERT(value_which_is_always_smaller_than_4 < 4)

where Q_ASSERT is Qts assert macro. Now clang, when seeing this warns me about it, because the comparison is always true. Nice that it can detect this, but that's the point of the assert statement. Can I somehow suppress the warning, but only in assert statements? I'd still liked to be warned in other places.

Inkane
  • 1,440
  • 1
  • 15
  • 32
  • 1
    @JoachimPileborg: The OP wants the warning in other places. `-Wnotautological-compare` will suppress the warning everywhere. – Nawaz Apr 07 '13 at 16:07
  • 3
    If clang can detect this, it means `value_which_is_always_smaller_than_4` is a compile-time constant. In that case, you can use compile time assertions (like `static_assert` in C++) to assert on their value, which is certainly better than a runtime assertion. – Shahbaz Jun 16 '17 at 15:17
  • -Wno-tautological-compare – tangkk Jun 25 '19 at 10:49

2 Answers2

13

You can define a new macro to wrap Q_ASSERT and automatically silence the warning using #pragma clang diagnostic ignored:

#define STR(x) #x
#define PRAGMA(x) _Pragma(STR(x))
#define MY_ASSERT(x) PRAGMA(clang diagnostic push) \
PRAGMA(clang diagnostic ignored "-Wtautological-compare") \
Q_ASSERT(x) \
PRAGMA(clang diagnostic pop)

Now just doing

MY_ASSERT(3<4)

should not produce a warning.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
5

You can disable it for the entire file by adding -Wno-tautological-compare to the Clang command line (after flags such as -Wall that turn warnings on). The disadvantage of this method is that the warning is now disabled everywhere in that translation unit, not just for the Q_ASSERT(...) macro instances.

Another, more tedious but fine grained, method is to wrap every instance of the macro that generates this warning with the following:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"

Q_ASSERT(value_which_is_always_smaller_than_4 < 4)

#pragma clang diagnostic pop
Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • 1
    The command line flags `-Wno-tautological-constant-compare` can also assigned to `CFLAGS` or `CXXFLAGS` if someone use GNU autotools – alijandro Jul 08 '19 at 12:00