g++ generates warnings for unused local variables. Is it possible to have g++ warn for unused class member variables and/or global variables?
class Obj {
public:
Obj(int a, int b) : num1(a), num2(b) {}
int addA(int i) {
return i + num1;
}
private:
int num1;
int num2;
};
How do I get g++ to warn me that num2
is unused?
UPDATE: I am currently compiling with:
g++ -Wall -Wextra -pedantic *.cc -o myprogram
Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.
To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.
Unused variables are a waste of space in the source; a decent compiler won't create them in the object file. Unused parameters when the functions have to meet an externally imposed interface are a different problem; they can't be avoided as easily because to remove them would be to change the interface.
Unused variable warnings are emitted during compiletime and should be a hint to you as the developer, that you might have forgotten to actually process a value that you have bound to a name. Thats the main reason for the warning.
Clang's -Wunused-private-field
enables the warning you're asking for. On your code base, it shows:
$ clang -Wunused-private-field /tmp/nic.cpp
/tmp/nic.cpp:10:22: warning: private field 'num2' is not used [-Wunused-private-field]
int num2;
^
1 warning generated.
I'm not aware of any such warning. Additionally I'll speculate that the reason it doesn't exist is because it can't be reliably generated in all cases, so they elected to not spend effort making it work for some subset of cases. For example, if the class friend
s another function that's in a library, the compiler would have no way of knowing if that library mutated any particular class attribute or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With