Skip to content

Trick C++ on Unused Variables

December 24th, 2015 - Software(1 min)

If you enable warning on unused method parameters ( -Wextra or -Wunused) and you get warnings in method parameters, you’re supposed to change the signature. Sometimes this is not OK and you still need the build to pass cleanly.

Java has the glorious @SuppressWarnings, so my best and most portable solution is to define a macro:

#define UNUSED(expr) do { (void)(expr); } while (0)

Then, you use it in the body of your function like this:

int method(int unused_param) {
    UNUSED(unused_param);

    // ...

    return 0;
}

This will trick the compiler to think the variable is used and it’ll be optimised out as well.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: