The following file foo.c
is a simplified version of a subtler bug I found in my code.
int b;
void bar(int a);
void foo(int a)
{
bar(a);
a = 42;
}
The line a = 42
is in fact a typo in my code: I meant b = 42
. I don't expect the compiler to detect that I made a typo, but I would like the get a warning that I am assigning to a local variable (or a function parameter) that is not going to be used anymore. If I compile this file with
% gcc-4.6 -Wall -Wextra -pedantic -O3 -c foo.c
I get absolutely no warning. Inspecting the generated code shows that the assignment a = 42
is not performed, so gcc
is perfectly well aware that this instruction is useless (hence potentially bogus). Commenting the call to bar(a);
does produce a warning warning: parameter ‘a’ set but not used [-Wunused-but-set-parameter]
, so it seems like gcc
will not warn as long as a
is used somewhere in the function, even if it is before the assignment.
My questions:
bar
removed.)A local variable is defined (by an assignment) but never used. It is sometimes necessary to have a variable which is not used. These unused variables should have distinctive names, to make it clear to readers of the code that they are deliberately not used.
If there are a large number of unused variables or functions, which can happen with ported code, you can add the -Wno-unused compiler option to your makefile. This option suppresses all unused warnings.
It means you have given answer a value, but not referenced it elsewhere. Meaning you are not using answer elsewhere in your program. You fix it by referencing answer from another part of your program.
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.
There is no gcc
or clang
option to my knowledge that can warn about this useless assignment.
PC-Lint
on the other hand is able to warn in this situation.
Warning 438 Last value assigned to variable 'Symbol' not used -- A value had been assigned to a variable that was not subsequently used. The message is issued either at a return statement or at the end of a block when the variable goes out of scope.
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