C语言--常量、变量

【C语言】

操作符https://mp.csdn.net/editor/html/115218055

数据类型https://mp.csdn.net/editor/html/115219664

自定义类型:结构体、枚举、联合https://mp.csdn.net/editor/html/115373785

变量、常量https://mp.csdn.net/editor/html/115230188

分支、循环语句https://mp.csdn.net/editor/html/115234118

字符串+转义字符+注释https://mp.csdn.net/editor/html/115231391

指针https://mp.csdn.net/editor/html/115281303

数组https://mp.csdn.net/editor/html/115266750

函数https://mp.csdn.net/editor/html/115265396

 

内容来自   B站  C语言教学视频   https://www.bilibili.com/video/BV1RX4y1u7Zh

 

 

 

变量、常量

1.变量:

2.常量:


 

1.变量:

变量的作用域和生命周期
 
作用域
作用域( scope ),程序设计概念,通常来说,一段程序代码中所用到的名字并不总是有效 / 可用的 ,而限定这个名字的可用性的代码范围就是这个名字的作用域。
1. 局部变量的作用域是变量所在的局部范围。
2. 全局变量的作用域是整个工程。
 
生命周期
变量的生命周期指的是变量的创建到变量的销毁之间的一个时间段
1. 局部变量的生命周期是:进入作用域生命周期开始,出作用域生命周期结束。
2. 全局变量的生命周期是:整个程序的生命周期。


 局部变量 全局变量 

 #include <stdio.h>
  int num2 = 20;// 全局变量 定义在代码块({})之外的变量
  int main()
  {  
    int num1 = 10;//局部变量 定义在代码块({})内部的变量     
    return 0;
   }


 注意   
  局部变量的作用域,只作用在相应的代码块之内

int main()
 {
       {
          int a = 10;
       }
       printf("%d", a);  //此时不能打印a
       return 0;
  }


   extern 声明外部符号的      ?此处有点疑惑 好像作用另外一个源文件 视频3.初始C语言(3)片段4_0s

#include <stdio.h>
   int main()
   { 
       extern int g_val;
       printf("g_val = %d", g_val);
       return 0;
   }


  
  局部变量和全局变量的名字建议不要相同,易产生误会,产生bug,当局部变量和全局变量相同时,局部变量优先

#include <stdio.h>
  int a = 100;
  int main()
  {  
      int a = 10;
      printf("%d\n", a);  //输出为10
      return 0;
  }
  


  
  计算两个数的和

#include <stdio.h>
  int main()
  {  
     int num1 = 0;
     int num2 = 0;
     int sum = 0;
     //输入数据 使用输入函数scanf
     scanf("%d%d", &num1, &num2); //取地址符号&
     int sum = 0;
     sum = num1 + num2; 
     printf("sum = %d\n", sum);
     return 0;
  }

 

 

2.常量:

分类:    字面常量       const修饰的常变量——常属性        #define定义的标识符常量       枚举常量--枚举--一一列举
 

 #include <stdio.h>
  int main()
  { 
    3;//字面常量
    const int num = 4;//num是变量,但是又有常属性,所以我们说num是常变量
    printf("%d\n", num); //此时打印为4
    num = 8;
    printf("%d\n", num);//打印还是4,因为前面有const修饰
    return 0;
  }  

 

  #include <stdio.h>
  #define MAX 10  //#define定义的标识符常量   此时MAX相当于10
   enum Color  // 创建了一个枚举常量类型
   {
     red,
     yellow,
     blue
   };

   int main()
  { 
    enum Color color = blue; //枚举常量Color  枚举常量名字color
    int arr[MAX] = {0};
    printf("%d\n", MAX);
    return 0;
  }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值