Force GCC to throw an error when an assignment (wrapped in parenthesis) is used as truth value

Viewed 135

I'm trying to find a GCC compiler flag that would cause GCC to refuse to compile the following code:

# include <stdio.h>

int main()
{
    int x = 1;

    if( (x = 10) ) {
        printf("x is 10");
    } else {
        printf("x is not 10");
    }
    return 0;
}

The above code will compile with no warnings:

gcc -Wall -Werror -O3 -o x.exe x.c

Specifically, I want GCC to barf at the line if( (x = 10) ). If I remove the inner brackets, GCC will break due to -Werror

gcc -Wall -Werror -O3 -o x.exe x.c
x.c: In function 'main':
x.c:7:9: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
     if( x = 10 ) {
         ^
cc1.exe: all warnings being treated as errors

What I'm looking for is a way to force GCC to refuse to compile the code even when the brackets are present.

Thanks!

1 Answers

There doesn't seem to be any way to convince GCC to do this. -Wall -Wextra doesn't warn for your example code, and I didn't see any other warning options that would seem relevant. (As noted in comments, by GCC's design, generally the only way to make it reject otherwise legal code is to find a warning option that the code triggers, and then use -Werror to upgrade the warning to an error.)

As another data point, clang offers a fairly similar set of warnings as GCC, and it has the bonus of the -Weverything option that enables every warning it provides. (It'd be nice if GCC had such a thing too.) But clang -Weverything doesn't give any warnings for your code either.. That seems like pretty good evidence that nobody in these communities has implemented a warning for code like yours.

I agree it seems like something that would be useful, so it might be worth filing a feature request for GCC and/or clang (or seeing if someone already has).

Related