Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help regarding macro definition

Im reading c++ code, i have found such definition

#define USE_VAL(X) if (&X-1) {}

has anybody idea, what does it mean?

like image 836
Waleed A Avatar asked Dec 15 '15 09:12

Waleed A


1 Answers

Based on the name, it looks like a way of getting rid of an "unused variable" warning. The intended use is probably something like this:

int function(int i)
{
  USE_VAL(i)
  return 42;
}

Without this, you could get a compiler warning that the parameter i is unused inside the function.

However, it's a rather dangerous way of going about this, because it introduces Undefined Behaviour into the code (pointer arithmetic beyond bounds of an actual array is Undefined by the standard). It is possible to add 1 to an address of an object, but not subtract 1. Of course, with + 1 instead of - 1, the compiler could then warn about "condition always true." It's possible that the optimiser will remove the entire if and the code will remain valid, but optimisers are getting better at exploiting "undefined behaviour cannot happen," which could actually mess up the code quite unexpectedly.

Not to mention that fact that operator& could be overloaded for the type involved, potentially leading to undesired side effects.

There are better ways of implementing such functionality, such as casting to void:

#define USE_VAL(X) static_cast<void>(X)

However, my personal preference is to comment out the name of the parameter in the function definition, like this:

int function(int /*i*/)
{
  return 42;
}

The advantage of this is that it actually prevents you from accidentally using the parameter after passing it to the macro.

like image 81
Angew is no longer proud of SO Avatar answered Sep 17 '22 23:09

Angew is no longer proud of SO