简体   繁体   中英

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?

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.

Typically it's to avoid an "unused return value" warning. Even if the usual "cast to void" idiom normally works for unused function parameters, gcc with -pedantic is particularly strict when ignoring the return values of functions such as fread (in general, functions marked with __attribute__((warn_unused_result)) ), so a "fake if " is often used to trick the compiler in thinking you are doing something with the return value.

A macro is a pre-processor directive, meaning that wherever it's used, it will be replaced by the relevant piece of code.

and here after USE_VAL(X) the space it is explain what will USE_VAL(X) do.

first it take the address of x and then subtract 1 from it. if it is 0 then do nothing.

where USE_VAL(X) will used it will replaced by the if (&X-1) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM