سؤال

So I've seen a number of threads explaining how to avoid unreferenced parameter warnings, for instance:

Avoid warning 'Unreferenced Formal Parameter'
C++ What is the purpose of casting to void?

But what I'm wondering is whether the compiler will do anything different based on which approach is used. For example, will the compiled output for the following three situations be any different?

void Method(int /*x*/)
{
    // Parameter is left unnamed
}

void Method(int x)
{
    x;  // This would be the same as UNREFERENCED_PARAMETER(x);
}

void Method(int x)
{
    (void)x;  // This would be the same as _CRT_UNUSED(x);
}

I'm most interested in this from the standpoint of what the compiler will do, but if you feel strongly for one approach over the others, I'm happy to hear those arguments as well.

هل كانت مفيدة؟

المحلول 2

I can see no reason why the compiler would treat any of those different. But the only way to tell for sure for your compiler is for you to look at the output of your compiler.

I would prefer the first option since this situation (unused parameters) is what that language feature was designed for.

نصائح أخرى

Of the three, the last option, (void)x; is preferable in most cases.

The first option, leaving the parameter unnamed, is acceptable, but often it is useful for the parameter to have a name for debugging purposes (e.g., even if you aren't using the parameter in the function, you might be interested in its value when debugging). There are cases where this option is fine, though, e.g. when doing tag dispatching.

The second option, x; may cause other warnings. Visual C++ will issue warning C4555 for this code:

warning C4555: expression has no effect; expected expression with side-effect

By casting x to void via (void)x;, this warning is suppressed. (Note that this warning is off by default; this warning must be expressly enabled via #pragma or command-line option.)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top