alan
alan

Reputation: 1

GCC's scope depth representation method

The depth of the description file_scope in GCC is 1, and the external_scope is 0. I wrote a program to test the results.

int main() {
        int a;
        {
                int b;
        }
        {
                int c;
        }
        if (1) {
                int d;
        }
}

The depth of variable a is 2, and both b and c are 3, but the depth of variable d is 5.

Why is the depth of variable d not 3 or 4?

Upvotes: 0

Views: 113

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

According to the C Standard (6.8.4 Selection statements)

3 A selection statement is a block whose scope is a strict subset of the scope of its enclosing block. Each associated substatement is also a block whose scope is a strict subset of the scope of the selection statement.

Here is a demonstration program.

#include <stdio.h>

int main( void )
{
    if ( sizeof( struct A { long x; } ) == sizeof( long long ) )
    {
        struct A
        {
            long x;
        } a;

        printf( "sizeof( a ) within if = %zu\n", sizeof( a ) );
    }
    else
    {
        struct A
        {
            long long x;
        } a;
        
        printf( "sizeof( a ) within else = %zu\n", sizeof( a ) );
    }
}

Within the if statement there is introduced the type specifier struct A

    if ( sizeof( struct A { long x; } ) == sizeof( long long ) )

In the substatements of the if statement there are also introduced type specifiers with the same name that hide the type specifier introduced in the if statement.

So if to count scopes as you are doing then there are the following scopes;

  1. file scope
  2. the block scope starting with the parameter list of the definition of main
  3. the scope of the if statement
  4. and the scope of the if statement substatements

gcc can add its own scope for the compound statement of the if statement.

Upvotes: 1

Related Questions