zoukankan      html  css  js  c++  java
  • C语言讲义——全局变量和局部变量

    局部变量

    普通的局部变量也叫动态变量,默认有个关键字叫auto,可以省略。有两种形式:
    1.函数内的局部变量
    2.复合语句内的局部变量:for(int i = 0; i<5; i++){…}


    静态局部变量只能在函数内定义,如:static int a;
    函数外不能用,但每次调用会保留上一次的值


    #include <stdio.h>
    void buy() {
    	auto int timesAuto = 1;// 普通局部变量(auto可以省略)
    	printf("买%d件
    ",timesAuto++);
    
    	static int timesStatic = 1;// 静态局部变量
    	printf("-----static买%d件
    ",timesStatic++);
    }
    
    main() {
    	int i;
    	for(i= 1; i<=5; i++) {
    		buy();
    	}
    }
    
    买1件
    -----static买1件
    买1件
    -----static买2件
    买1件
    -----static买3件
    买1件
    -----static买4件
    买1件
    -----static买5件
    

    全局变量

    普通全局变量:函数外定义,各文件都能使用,无需头文件引入,需extern引入
    静态全局变量:函数外定义,自己文件内各函数都可使用,其他文件extern也用不了

    f2.c

    int a = 1;
    // 静态全局变量不能在其他文件中使用
    static int b = 2;
    

    main.cpp

    #include <stdio.h>
    
    int main(int argc, char** argv) {
    	extern int a;
    	printf("全局变量a = %d
    ", a);
    //	静态全局变量不能在其他文件中使用
    //	extern int b;
    //	printf("static全局变量b = %d
    ", b);
    	return 0;
    }
    

    同名变量

    局部变量会覆盖同名的全局变量。

    #include <stdio.h>
    int  n=1;
    main() {
    	printf("外部变量 n = %d
    ",n);
    	int  n=2;
    	printf("局部变量 n = %d
    ", n);
    }
    
    外部变量 n = 1
    局部变量 n = 2
    

    C语言内存分区

    BSS:Block Started by Symbol

  • 相关阅读:
    强化学习
    nginx环境准备
    全面解读PHP-数据结构
    全面解读PHP-数据库缓存
    跨域问题的解决方法
    使用 apt-get 清理
    怎样用 Bash 编程:逻辑操作符和 shell 扩展
    怎样用 Bash 编程:语法和工具
    使用 split 命令分割 Linux 文件,使用 cat 合并文件
    通过tar包解压安装docker
  • 原文地址:https://www.cnblogs.com/tigerlion/p/11191493.html
Copyright © 2011-2022 走看看