Search code examples
cgccc89

Is the GCC option -Wdeclaration-after-statement purely stylistic?


Is the option -Wdeclaration-after-statement stylistic only? By that I mean, if I macro'd all cases in my C code where a variable was defined and I initialized them in them in the same fashion migrating from this older style C90 to the newer C99 style, would that code be byte-for-byte the same?

Here is how the option -Wdeclaration-after-statement is documented (from man gcc):

Warn when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90.

And it allows you to take code like

int a;
{
    a = 42;
    printf( "%d", a );
}

and turn it into

int a = 42;
printf( "%d", a );

This is a follow-up to my question here.


Solution

  • No, it's not. For example, the above two snippets will compile byte-for-byte the same. So will the foo and bar below, but baz will not. Here is a link to GodBolt. This demonstrates that hoisting the initialization to the declaration may NOT produce the same code

    void foo () {
        int a;
        {
            if ( 1 ) {
                a = 42;
                printf( "%d", a );
            }
            else {
                a = 42;
                printf( "%d", a );
            }
        }
    }
    
    void bar () {
        int a = 42;
        {
            if ( 1 ) {
                printf( "%d", a );
            }
            else {
                printf( "%d", a );
            }
        }
    }
    
    void baz () {
        int a;
        {
            if ( rand() > 0 ) {
                a = 42;
                printf( "%d", a );
            }
            else {
                a = 42;
                printf( "%d", a );
            }
        }
    }