Example of function scope

Viewed 80

The following would be an example of block scope:

int func(int a) {
    int b;     
    ...
              
}             // end of block scope for a & b

What would be an example of function scope, which I believe is applied to goto labels?

2 Answers

From the C standard, 6.2.1 Scopes of identifiers:

A label name is the only kind of identifier that has function scope. It can be used (in a goto statement) anywhere in the function in which it appears, and is declared implicitly by its syntactic appearance (followed by a : and a statement).

The reason it is different than block scope is that it ignores blocks:

void f(int a) {
    {
        increase_a: ++a;
    }

    if (a)
        goto increase_a;
}

This compiles because increase_a is visible by the goto statement, which wouldn't be the case if it had block scope.

While these aren't too common, here would be an example:

#include<stdio.h>

int main(void)
// [start outer-scope]
{
    int a=4;
    if (a == 4)

        // [start inner-scope]
        {
            int b=7;
         label:
            b+=1;
            printf("Hello\n");
            if (b > 10) goto end;
         }                          // 1. b has (inner) block scope, it ends here

    goto label;

end:
    return 0;
}                                   // 2. a has (outer) block scope, it ends here
                                    // 3. even though "label" is defined within the
                                    // inner block, it has function scope, so
                                    // it is viewable within the entire function, as-if
                                    // it had (outer) block scope
                                   

$ ./run
Hello
Hello
Hello
Hello
$

Related