C语言学习笔记[17]:常见关键字②

常见关键字

auto   break   case   char   const   continue   default   do   double   else   enum   extern   float   for   goto   if   int   long   register   return   short   signed   sizeof   static   struct   switch   typedef   union   unsigned   void   volatile   while

  • typedef:类型重定义

就是对已知的类型进行重新定义一个别名

#include <stdio.h>

typedef unsigned int u_int;
// 定义了一个新的类型 u_int 类型,它是 unsigned int 类型的别名
int main()
{
    unsigned int a = 10;
    u_int b = 20;//此处的 u_int 类型就是 unsigned int 类型
    return 0;
}
  • static:静态的
  1. static 修饰局部变量
  2. static 修饰全局变量
  3. static 修饰函数

statci 修饰局部变量

首先看下面的这段代码,static 未修饰局部变量时:

#include <stdio.h>

void test()
{
    //a 创建
    int a = 1;
    a++;
    printf("%d ", a);
    //a 销毁
}

int main()
{
    int i = 0;
    while (i < 10)
    {
        test();
        i++;
    }
    return 0;
}

运行结果是10个2,因为每次进入 test() 函数都要创建一次 a 导致 a 的值一直不变。

而当 a 被 static 修饰以后就不一样了:

#include <stdio.h>

void test()
{ 
    static int a = 1;
    a++;
    printf("%d ", a);
}

int main()
{
    int i = 0;
    while (i < 10)
    {
        test();
        i++;
    }
    return 0;
}

运行结果是 2 到 10

被 static 修饰的 a 第一次进入 test() 函数时,被创建使得 a = 1,经过 a++ 后输出 a 为 2 ,但是第二次进入 test() 函数时,由于 a 被 static 修饰,则 a 不会重新创建,会使用上一次出 test() 函数时的 a 的值,即 a = 2,又进行 a++ ,输出 a = 3...以此类推

由此可知,static 修饰的局部变量,改变了局部变量的声明周期(本质上改变了该局变量的存储位置) 

已知内存的分布是如图所示:

如果需要一个变量出了其作用域不销毁,下次进入其作用域继续使用,则需要被 static 修饰。 

static 修饰全局变量

//add0.c 中
static int g_val = 10;//全局变量
//test0.c 中
#include <stdio.h>

extern int g_val;//声明外部符号
int main()
{
    printf("g_val = %d\n", g_val);
    return 0;
}

static 修饰的全局变量,使得该全局变量只能在自己所在的源文件内部使用,其他源文件无法使用。

全局变量是有外部链接属性的,从而可以在不同源文件中使用,而被 static 修饰的全局变量,则变成了内部链接属性,因此不能再源文件中使用。

static 修饰函数

//add1.c文件
static int Add(int x, int y)
{
    return x + y;
}
//test1.c文件
#include <stdio.h>

extern int Add(int, int);//声明外部符号
int main()
{
    int a = 10;
    int b = 20;
    int sum = Add(a, b);//!报错
    printf("sum = %d\n", sum);
    return 0;
}

static 修饰的函数,使函数只能在自己所在的源文件中使用,不能在其他源文件中使用。

本质上 static 是将函数的外部链接属性变成了内部链接属性(和 static 修饰全局变量一样)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值