打卡学习C语言-static and typedef

static:

  • 修饰局部变量
    • 局部变量出了其作用域不被销毁
    • 本质上是改变了其存储位置,
      • static修饰的局部变量被放在了静态区
      • 没有static修饰的局部变量存放在栈区,
      •  影响了变量的生命周期,使其和整个程序的生命周期一样

  • 修饰全局变量
    • 没有static修饰的全局变量具有外部链接属性
    • static修饰的全局变量改变了其外部链接属性,变成了内部连接属性
    • 其他源文件不能访问到这个全局变量
    • 本文件内部不受影响
  • 修饰函数
    • 函数和全局变量相似
    • 函数也具有外部链接属性
    • static修饰的函数改变了其外部链接属性,成为了内部链接属性

没有static修饰的局部变量a,打印a,其结果为 10个 2 
#include <stdio.h>
void text()
{
    int a = 1;//变量进入作用域被创建
    a++;//
    printf("%d\n",a);//打印a,a的值为 10个 2
};//变量出作用域被销毁,不会保留

int main()
{
    int i = 0;
    while(i<10)
    {
        text();
        i++;
    }
    return 0;
}
static修饰局部变量:
#include <stdio.h>
void text()
{
    static int a = 1;//
    a++;//
    printf("%d\n",a);//2,3,4~~11
};

int main()
{
    int i = 0;
    while(i<10)
    {
        text();
        i++;
    }
    return 0;
}
没有static修饰的全局变量:

在外部文件创建int类型变量num赋值为2023

int num = 2023;

在main函数中打印num变量

#include <stdio.h>

extern int num;
int main()
{
	printf("%d\n", num);
	return 0;
}

引入外部符号:extern

extern int num;

打印结果为:2023 

static修饰的全局变量:

static int num = 2023;

再次打印num变量,报错

>------ 已启动生成: 项目: static, 配置: Debug x64 ------
1>num.c
1>static.obj : error LNK2001: 无法解析的外部符号 num
1>D:\c\vs2022\static\x64\Debug\static.exe : fatal error LNK1120: 1 个无法解析的外部命令
1>已完成生成项目“static.vcxproj”的操作 - 失败。
========== 生成: 0 成功,1 失败,0 最新,0 已跳过 ==========
========= 生成 开始于 2:55 PM,并花费了 01.212 秒 ==========

没有static修饰的外部函数:



int add(int x,int y)
{
	return x + y;
}

主函数

#include <stdio.h>


int main()
{
	int a = 10;
	int b = 20;
	int res = add(a, b);
	printf("%d\n", res);//30
	return 0;
}

static修饰的外部函数:


static int add(int x,int y)
{
	return x + y;
}

运行报错:

已启动生成...
1>------ 已启动生成: 项目: static, 配置: Debug x64 ------
1>num.c
1>static.obj : error LNK2019: 无法解析的外部符号 add,函数 main 中引用了该符号
1>D:\c\vs2022\static\x64\Debug\static.exe : fatal error LNK1120: 1 个无法解析的外部命令
1>已完成生成项目“static.vcxproj”的操作 - 失败。
========== 生成: 0 成功,1 失败,0 最新,0 已跳过 ==========
========= 生成 开始于 3:12 PM,并花费了 01.081 秒 ==========
typedef:
unsigned int num = 2023;

类型重新定义

typedef unsigned int ye;

在类型定义之后,标识符 ye可作为类型 unsigned int的缩写

ye num1 = 2024;

对结构体使用 typedef 来定义一个新的数据类型

typedef struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} Book;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值