Search code examples
cgccclangcompiler-warningslibc

Why -Wunused-value does not catch a statement `true;`?


Given following C code:

#include <stdbool.h>

int main (void)
{
    true;
    return 0;
}

I expect that -Wunused-value would cause a warning at line 5: true;
because this statement does nothing and can be a source of the bug
but it goes through silent - in fact -Wunused -Wall -Wextra does not catch it.


For comparison, something like this:

#define TRUE 1

int main (void)
{
    TRUE;
    return 0;
}

or this:

int main (void)
{
    1;
    return 0;
}

would trigger the proper warning as one would expect (GCC 14.2):

<source>: In function 'main':
<source>:3:5: warning: statement with no effect [-Wunused-value]
    3 |     1;
      |     ^

So I started digging; I thought this might be a regression in GCC.
I went from GCC 14.2 down to the very, very old releases
and seems like GCC 3.4.6 was the last one where the warning appears as expected.

I thought about reporting this to GCC but then I checked Clang
and Clang also does not produce any warning about this since Clang 3.0.0

See: https://godbolt.org/z/T361d3ad6


Although I was able to find similar bugs on GCC mailing list, e.g.
https://gcc.gnu.org/pipermail/gcc-bugs/2021-November/765405.html
I cannot believe that two major compiler vendors simply have the same bug for a long time.

I suspect this is happening since true is a macro defined inside of libc headers
and compiler generally do not yell about issues coming from libc
but since this one is happening inside of my code I'm a bit concerned.
I wasted a lot of time on finding this, then realizing the warning should catch it.


Is there any rationale on why this is happening?
Or is this just a bug/regression in the compiler that should be reported?


EDITs / NOTEs:

  • MSVC invoked with /Wall /std:c11 does NOT have this issue
  • Since I already have a lot of information, I reported this to LLVM/clang (seems like the easiest place to report it for now) - https://github.com/llvm/llvm-project/issues/106867
  • If I won't get any response on the bug above, I will send it to GCC
  • I do NOT believe that -Wsystem-header is a valid solution for this problem (see my comments under dbush answer for explanation)

Solution

  • This is GCC's bug.
    Several tickets describe this behavior as undesired:

    -Wsystem-headers should not be required in this case, as diagnosed construct occurs inside of user's code, not in system header. The macro itself comes from system header, but it is not expanded there.