Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress -Wtautological-compare warning

Tags:

c++

clang

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.

like image 963
Inkane Avatar asked Apr 07 '13 16:04

Inkane


People also ask

What does suppress warning mean?

Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class.

Why we use suppress warnings?

If we don't want to fix the warning, then we can suppress it with the @SuppressWarnings annotation. This annotation allows us to say which kinds of warnings to ignore. While warning types can vary by compiler vendor, the two most common are deprecation and unchecked.

Which number is used to suppress the warning in a code?

Use a #pragma warning (C#) or Disable (Visual Basic) directive to suppress the warning for only a specific line of code.


2 Answers

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.

like image 179
nneonneo Avatar answered Oct 21 '22 00:10

nneonneo


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
like image 20
Praetorian Avatar answered Oct 21 '22 00:10

Praetorian