C语言学习:常用关键字

1 typedef 

 typedef:类型重命名。

比如:

//将unsigned int重命名为uint_32;
typedef unsigned int	uint_32;
int main()
{
	//num1跟num2的类型定义是一样的;
	unsigned int num1 = 0;

	uint_32 num2 = 0;

	return 0;
}

2 static

static:修饰变量和函数

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

 2.1 修饰局部变量

//不加static
void test()
{
	int a = 0;
	a++;
	printf("a = %d\n", a);
	
}
int main()
{
	int i = 0;
	while(i < 10)
	{
		test();
		i++;
	}

	return 0;
}
//加static
void test()
{
	static int a = 0;
	a++;
	printf("a = %d\n", a);
	
}
int main()
{
	int i = 0;
	while(i < 10)
	{
		test();
		i++;
	}

	return 0;
}

        运行代码可见,加上static后,输出的a的值为1-10;而不加输出的值则一直为1。所以对于修饰局部变量的static的作用便是使所定义变量在整个程序中只初始化一次,延长所修饰变量生命周期。

 2.2 修饰全局变量

//不加static

//文件1
#include <stdio.h>
extern int a;
int main()
{
	printf("a = %d\n", a);
	return 0;
}

//文件2
#include <stdio.h>

int a = 0;
//加static

//文件1
#include <stdio.h>
extern int a;
int main()
{
	printf("a = %d\n", a);
	return 0;
}

//文件2
#include <stdio.h>

static int a = 0;

        运行代码可见,不加static,a的值能够正常输出;而加上后则有一个报错。所以对于修饰全局变量的static的作用便是使所定义变量仅仅只能在本文件中调用,而无法再在外部文件中调用。

 2.3 修饰函数

//不加static

//文件1
#include <stdio.h>

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

	return 0;
}

//文件2
#include <stdio.h>

void test()
{
	int a = 0;
	a++;
	printf("a = %d\n", a);
}
//加static

//文件1
#include <stdio.h>

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

	return 0;
}

//文件2
#include <stdio.h>

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

        运行代码可见,不加static,外部函数test()能够正常调用;而加上后则有一个报错。所以对于修饰函数的static的作用便是使所定义函数仅仅只能在本文件中调用,而无法再在外部文件中调用。

3 extern

extern:声明外部定义的变量、函数或其他符号。

 比如:

//文件1
#include <stdio.h>
extern int a;//调用当前文件未声明的变量
int main()
{
	printf("a = %d\n", a);
	return 0;
}

//文件2
#include <stdio.h>

int a = 0;

4 define

define;用来将一个标识符定义为一个字符串 , 该标识符被称为宏名, 被定义的字符串称为替换文本。

  1. 不带参宏定义        #define 宏名 字符串
  2. 带参宏定义            #define 宏名(参数表) 字符串

4.1 不带参宏定义 

#include <stdio.h>

//定义一个常量
#define PI 3.1415f //宏定义,定义PI = 3.1415

//定义一个不带参的函数
#define Add (a + b)//定义Add = a + b

int main()
{
	printf("PI = %f\n", PI);

	int a = 1, b = 2;
	int x = 0;

	x = Add * Add;
	printf("x = %d\n", x);
	return 0;
}

        但是需要注意的是宏定义是用宏名来表示一个字符串,在宏展开时又以该字符串取代宏名,这只是一种简单的代换,字符串中可以含任何字符,可以是常数,也可以是表达式,预处理程序对它不作任何检查。如有错误,只能在编译已被宏展开后的源程序时发现。

4.2 带参宏定义 

#include <stdio.h>

//定义一个带参的函数
#define Max(a, b) ((a>b)?(a):(b))//定义求最大值函数,如果a > b返回a,否则返回b。

int main()
{
	int max1 = 0, max2 = 0;

	max1 = Max(1, 3);//a < b,返回b
	printf("Max1 = %d\n", max1); 

	max2 = Max(2, 1);//a > b,返回a
	printf("Max2 = %d\n", max2);

	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值