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:
- Is there a way to tell GCC or Clang to produce a warning for such case? (I could not get clang 3.0 to produce any warning, even with the call to
barremoved.) - Is there a reason for the actual behavior? I.e, some cases were it is actually desirable to assign to local variables that will be thrown away by the optimizer?
There is no
gccorclangoption to my knowledge that can warn about this useless assignment.PC-Linton the other hand is able to warn in this situation.