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

  • 相关阅读:
    float浮动后,父级元素高度塌陷和遮盖问题
    Json
    测试连接数据库是否成功
    spark standalone zookeeper HA部署方式
    用NAN简化Google V8 JS引擎的扩展
    在Android上使用Google V8 JS 引擎
    数据可视化工具zeppelin安装
    kafka0.8.2以下版本删除topic
    kafka迁移数据目录
    scala2.10.x case classes cannot have more than 22 parameters
  • 原文地址:https://www.cnblogs.com/tigerlion/p/11191493.html
Copyright © 2011-2022 走看看