zoukankan      html  css  js  c++  java
  • [C][变量作用域]语句块

    概述

         C语言作用域有点类似于链式结构,就是下层能访问上层声明的变量,但是上层则不能访问下层声明的变量

    #include <stdio.h>
    #define TRUE 1
    
    int main(void)
    {
        if (TRUE)
        {
            int x = 2;
            if (TRUE)
            {
                printf("%d
    ", x);\output: 2
            }
        }
    }

         就像上述例子,第二个if语句块是可以访问到第一个if语句块中声明的变量x的;

         C语言一般把变量作用域归结为4个:

          1.文件作用域;

          2.语句块作用域(所有大括号的语句块,如if/for/while等);

          3.函数原型作用域;

          4.函数作用域;

         当当前层声明了一个跟上层标识符和命名空间一模一样的变量时,当前层的行为是隐藏上层的声明,启用当前层的声明,而当代码返回上层,则继续沿用上层生效的声明

    #include <stdio.h>
    #define TRUE 1
    
    int main(void)
    {
        if (TRUE)
        {
            int x = 2;
            if (TRUE)
            {
                int x = 3;
                printf("%d
    ", x);\output: 3
            }
            printf("%d
    ", x);\output: 2
        }
    }

         当不带类型声明符时,当前层可以访问包括改变上层的变量:

    #include <stdio.h>
    #define TRUE 1
    
    int main(void)
    {
        if (TRUE)
        {
            int x = 3;
            if (TRUE)
            {
                x = 2;
                printf("%d
    ", x);//output: 2
            }
            printf("%d
    ", x);//output: 2
        }
    }

         又例如调用函数改变:

    #include <stdio.h>
    #define TRUE 1
    
    int x = 1;
    void chx(void);
    
    int main()
    {
    
        chx();
        if (TRUE) {
            printf("%d
    ", x);//output: 3
        }
    }
    
    void chx(void)
    {
        x = 3;
    }

         对于extern外部变量,规则也是适用的:

    /*file a.c*/
    int x = 2;
    /*file b.c*/
    #include <stdio.h>
    #define TRUE 1
    
    extern x;
    void chx(void);
    
    int main()
    {
        printf("%d
    ", x);\output: 2
        chx();
        if (TRUE) {
            printf("%d
    ", x);\output: 3
        }
    }
    
    void chx(void)
    {
        x = 3;
    }

         以上两个规则对于4个变量作用域都有效,整个结构类似于这样:

         

  • 相关阅读:
    shell75叠加
    shell73while ping测试脚本
    shell72while读文件创建用户
    shell70批量修改远程主机的ssh配置文件内容
    shell68批量创建用户(传多个参数)
    js限制input输入
    php获取textarea的值并处理回车换行的方法
    strtr对用户输入的敏感词汇进行过滤
    mysql执行语句汇总
    js倒计时防页面刷新
  • 原文地址:https://www.cnblogs.com/yiyide266/p/10295285.html
Copyright © 2011-2022 走看看