1

I'm using the clang-based compiler in C++ Builder XE8 (--version reports it as Embarcadero Technologies Inc. clang version 3.1 (35091.dcc1b50.3081e8f) (based on LLVM 3.1svn)).

My code contains comparisons of unsigned integral values with macros, in the vein of myUnsignedInt >= MY_MACRO, which can generate always-true or always-false warnings when MY_MACRO is 0. I know clang has ways to silence certain other warnings by being in some way explicit about your intentions -- if (foo = bar) warns, but if ((foo = bar)) doesn't -- so is there a way to be explicit about a comparison like this (in clang specifically)?

alcedine
  • 909
  • 5
  • 18
  • Have you considered writing code that makes sense? – user207421 Nov 03 '15 at 08:21
  • 1
    @EJP Having an `x >= MIN_VALID_VALUE && x <= MAX_VALID_VALUE` in generic code makes perfect sense, even if in the concrete case it turns out that the types involved aren't signed and `MIN_VALID_VALUE` can be determined at compile time to be zero. –  Nov 03 '15 at 08:29
  • http://stackoverflow.com/questions/1297609/overloading-friend-operator-for-template-class – n. m. could be an AI Nov 03 '15 at 10:25

3 Answers3

0

Is there a reason why you're using macro's instead of const int MY_CONSTANT ?

There's no formal way to silence warnings. Compilers could warn you about your use of whitespace, if they'd want to. Thus the const suggestion isn't a guarantee that the warning will be solved. However, macro's are a literal replacement, so the compiler doesn't even know why it sees the pointless statement if (x>=0), whereas it does see if (x>=c) with c==0 so it at least has a better understanding.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • I'm asking about clang and its warnings specifically (sorry if that wasn't clear). Hence the analogy to the assignment in the `if` body, for which an equivalent, more explicit form is specifically understood as a sort of "_sic_". – alcedine Nov 03 '15 at 08:48
0

Try using a helper function, something like this:

bool ge(unsigned a, unsigned b) { return a >= b; }
...
  if (ge(num, 0u)) ...

It should be optimized away as trivial.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
0

I prefer a generic programming approach to using #pragma directives. I ended up defining something like this:

#include <type_traits>
template<class X,bool b>struct NegativeClass{
  static bool test(X x);};
template<class X>struct NegativeClass<X,0>{
  static bool test(X){return 0;}};
template<class X>struct NegativeClass<X,1>{
  static bool test(X x){return x<0;}};
template<class X>bool negative(X x){
  return NegativeClass<X,std::is_signed<X>::value>::test(x);}

Now you can use this code fragment:

if(negative(x))throw "Error : x is negative";

This works when x is a built-in type, whether x is signed (in which case it does the test) or unsigned (which compiles if(0)...). This sort of approach can be adapted to other situations.