块范围

如果标识符的相应声明出现在块内(函数定义中的参数声明适用),则标识符具有块作用域。范围在相应块的末尾结束。

具有相同标识符的不同实体不能具有相同的范围,但范围可能重叠。在重叠范围的情况下,唯一可见的范围是在最内部范围内声明的范围。

#include <stdio.h>

void test(int bar)                   // bar has scope test function block
{
    int foo = 5;                     // foo has scope test function block
    {
        int bar = 10;                // bar has scope inner block, this overlaps with previous test:bar declaration, and it hides test:bar
        printf("%d %d\n", foo, bar); // 5 10
    }                                // end of scope for inner bar
    printf("%d %d\n", foo, bar);     // 5 5, here bar is test:bar
}                                    // end of scope for test:foo and test:bar

int main(void)
{
    int foo = 3;         // foo has scope main function block

    printf("%d\n", foo); // 3
    test(5);
    printf("%d\n", foo); // 3
    return 0;
}                        // end of scope for main:foo