Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to suppress A "Unused variable x" warning? [duplicate]

Tags:

c

gcc

What is the best/neatest way to suppress a compiler (in this case GCC) like "Unused variable x" warning?

I don't want to give any certain flags to GCC to remove all these warnings, just for special cases.

like image 354
gustaf Avatar asked Aug 05 '10 18:08

gustaf


People also ask

How do I stop unused variable warning?

By default, the compiler does not warn about unused variables. Use -Wunused-variable to enable this warning specifically, or use an encompassing -W value such as -Weverything . The __attribute__((unused)) attribute can be used to warn about most unused variables, but suppress warnings for a specific set of variables.

How do you fix unused variables in Python?

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.

What does unused variable mean in C?

No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.

What is an unused variable?

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.


2 Answers

(void) variable might work for some compilers.

For C++ code, also see Mailbag: Shutting up compiler warnings where Herb Sutter recommends using:

template<class T> void ignore( const T& ) { }  ...  ignore(variable); 
like image 169
jamesdlin Avatar answered Sep 29 '22 22:09

jamesdlin


Do not give the variable a name (C++)

void foo(int /*bar*/) {     ... } 

Tell your compiler using a compiler specific nonstandard mechanism

See individual answers for __attribute__((unused)), various #pragmas and so on. Optionally, wrap a preprocesor macro around it for portability.

Switch the warning off

IDEs can signal unused variables visually (different color, or underline). Having that, compiler warning may be rather useless.

In GCC and Clang, add -Wno-unused-parameter option at the end of the command line (after all options that switch unused parameter warning on, like -Wall, -Wextra).

Add a cast to void

void foo(int bar) {     (void)bar; } 

As per jamesdlin's answer and Mailbag: Shutting up compiler warnings.

like image 23
3 revs, 2 users 83% Avatar answered Sep 29 '22 20:09

3 revs, 2 users 83%