Using the -Wunused-parameter flag, you can enforce __unused for unused parameters, as a compiler optimization. The following code causes two warnings:
#include <stdio.h>
int main(int argc, char **argv) {
printf("hello world\n");
return 0;
}
These warnings are fixed by adding __unused the unused arguments.
#include <stdio.h>
int main(int __unused argc, char __unused **argv) {
printf("hello world\n");
return 0;
}
When you use a parameter marked __unused, clang 4.1 does not warn or error.
#include <stdio.h>
int main(int __unused argc, char __unused **argv) {
printf("hello world. there are %d args\n", argc);
return 0;
}
The same behavior is exhibited using __attribute__((unused))
.
int main(int __attribute__((unused)) argc, char __attribute__((unused)) **argv) {
Is there a way to warn or error on __unused? What would happen should you accidentally leave an __unused on a used parameter? In the above example argc
appears to have the correct value, although it could be the compiler not taking advantage of the hint, and I wouldn't rely on this behavior without more understanding.
The __unused
attribute is intended to prevent complaints when arguments to functions/methods or functions/methods are unused, not to enforce their lack of use.
The term used in the GCC manual is:
This attribute, attached to a function, means that the function is meant to be possibly unused
And for variables:
This attribute, attached to a variable, means that the variable is meant to be possibly unused.
The most common use is for development against an interface - e.g. callbacks, where you may be forced to accept several parameters but don't make use of all of them.
I use it a bit when I'm doing test driven development - my initial routine takes some parameters and does nothing, so all the parameters take __attribute__((unused))
. As I develop it I make use of the parameters. At the end of development I remove them from the method, and see what shakes out.
Another way to skin this cat is to remove (or comment out) the name of the parameter.
int main ( int argc, char ** /* argv */ ) {
printf("hello world. there are %d args\n", argc);
return 0;
}
Now the compiler won't warn about argv
being unused, and you can't use it, because it has no name.