初识 11.常见关键字

11.常见关键字

C语言提供了丰富的关键字,这些关键字都是语言本身预先设定好的,用户自己是不能创造关键字的。

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

注:关键字,先介绍下面几个,后面遇到再展开

11.1关键字typedef

typedef 顾名思义是类型定义,这里应该理解为类型重命名。

比如:

#include<stdio.h>
struct Node
{
	int date;
	struct Node* next;
};
int main()
{
	unsigned int num = 0;
	struct Node n;
	return 0;
}

可写成以下形式

#include<stdio.h>
typedef unsigned int uint;
typedef struct Node
{
	int date;
	struct Node* next;
}Node;
int main()
{
	uint num = 0;
	Node n;
	return 0;
}

11.2关键字static

在C语言中:static是用来修饰变量和函数的

  1. 修饰局部变量–称为静态局部变量
  2. 修饰全局变量–称为静态全局变量
  3. 修饰函数–称为静态函数

11.2.1 修饰局部变量

代码1

#include <stdio.h>
void test()
{
	int a = 1;
	a++;
	printf("%d\n", a);
}
int main()
{
	int i = 0;
	while (i < 10)
	{
		test();
		i++;
	}
	return 0;
}

在这里插入图片描述
代码2

#include <stdio.h>
void test()
{
	static int a = 1;
	a++;
	printf("%d\n", a);
}
int main()
{
	int i = 0;
	while (i < 10)
	{
		test();
		i++;
	}
	return 0;
}

在这里插入图片描述
对比代码1和代码2理解static修饰局部变量的意义
结论:

static 修饰局部变量的时候,局部变量出了作用域,不销毁。本质上,static 修饰局部变量的时候,改变了变量的储存位置。影响了变量的生命周期,生命周期变长,和程序的生命周期一样。

11.2.2 修饰全局变量

代码1

add.c

int g_val = 100;

test.c

#include <stdio.h>
extern int g_val;//声明外部符号
int main()
{
	printf("%d\n", g_val);
	return 0;
}

在这里插入图片描述

代码2
add.c

static int g_val = 100;

test.c

#include <stdio.h>
extern int g_val;//声明外部符号
int main()
{
	printf("%d\n", g_val);
	return 0;
}

在这里插入图片描述
结论:

static 修饰全局变量的时候, 这个全局变量的外部链接属性就变成了内部链接属性, 使得这个全局变量只能在本源文件内使用, 其他源文件(.c)就不能再使用到这个全局变量了

11.2.3 修饰函数

代码1
add.c

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

test.c

#include <stdio.h>
extern int Add(int x, int y);
int main()
{
	int a = 10;
	int b = 20;
	int z = Add(a, b);
	printf("%d\n", z);
	return 0;
}

在这里插入图片描述

代码2
add.c

static int Add(int x, int y)
{
	return x + y;
}
#include <stdio.h>
extern int Add(int x, int y);
int main()
{
	int a = 10;
	int b = 20;
	int z = Add(a, b);
	printf("%d\n", z);
	return 0;
}

在这里插入图片描述

结论:

一个函数本来就是具有外部链接属性的,但是被static 修饰的时候,外部链接属性就变成了内部链接属性,其他源文件(.c)就无法使用了。

11.3关键字register

register为寄存器变量

#include <stdio.h>
int main()
{
	register int num = 3;//register在这里的作用:建议3存放在寄存器中
	return 0;
}
  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值