Friday, September 30, 2011

Suppress "unused parameter" warnings

Here's a way to suppress the annoying "unused parameter" warning given by the following code:
void aFunction(int unusedParameter)
{
    // Do something but ignore the 'unusedParameter'
}

I use this define:
#define CHECKED_UNUSED(x) (void)x

And then I surround unused parameter with it, right after the opening bracket of the function (so I can easy find and modify the parameter if I start using it):
#define CHECKED_UNUSED(x) (void)x

void aFunction(int unusedParameter)
{
    CHECKED_UNUSED(unusedParameter);
}


I looked at the generated assembly before and after and it didn't change:
                  aFunction(int):
00000000004007d4:   push %rbp
00000000004007d5:   mov %rsp,%rbp
00000000004007d8:   mov %edi,-0x4(%rbp)
15                }
00000000004007db:   pop %rbp
00000000004007dc:   retq
18                {


Disclaimer: use it only after you carefully checked that you really not need to use that parameter.
Unused parameters (and all the warnings in general) could really lead to a bug (or simple misunderstandings) in your code.

2 comments:

  1. In C++, the proper way to do that is to simply leave it unamed:

    void aFunction(int) {
    // no warnings here
    }

    ReplyDelete
  2. Well, let's say it IS named: if code is written by somebody else or for improved code readibility and "documentation" purposes it is the right way to do it.
    Moreover wrapping it in a define you can search "CHECKED_UNUSED" to track and keep in touch with all of them.

    ReplyDelete