常见关键字

本文深入探讨了C语言中的关键字,包括类型定义(typedef)、static的多种用途、以及宏定义的正确使用方法。通过实例解释了如何使用typedef进行类型重命名,static如何改变变量和函数的作用域与生命周期,以及#define在预处理阶段的应用。

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

# include <stdio.h>
# include <stdlib.h>
int main ()
{ typedef unsigned int unit_32;    //将unsigned int 重命名unit_32,所以unit _32也是一个类型名
	unsigned int num1=10;
    unit_32 num2=10;
	printf ("num1=%d\n",num1);   //观察num1和num2,这两个变量的类型是一样的
	printf ("num2=%d\n",num2);
	system ("pause");
   return 0; 
}

static
在c语言中:
1,修饰局部变量
2,修饰全局变量
3,修饰函数

        # include <stdio.h>
		# include <stdlib.h>
		void test ()
		{
		  static int i=0;    //输出结果  12345678910
		  //int i=0;        //输出结果   1111111111
		   i++;
		   printf ("%d",i);
		}
		int main ()
		{   int i=0;
			for (i=0;i<10;i++)
			{
			test ();
			}
			system ("pause");
			return 0;
		}

此程序本为输出10个1,但是在 static修饰局部变脸 i 后,它改变了 i的生命周期,让静态局部变量i 出了作用域依然存在,在程序结束时 ,i 的生命周期才结束。

   # include <stdio.h>
   	static int a=2000;  // static 修饰全局变量,编译出现连接性错误
	//int a=2000;
	int main ()
	{
		printf ("%d\n",a);  //输出结果为2000
		return 0;
	}

全局变量被 一个static 修饰,使得这个全局变量只能在本源文件内使用,不能在其他源文件内使用。(改变了作用域)

# include <stdio.h>
# include <stdlib.h>
static int add(int x,int y)   //static修饰函数时,会出现编译连接性错误
 // int add(int x,int y)  
 { 
  return x+y;
 }
int main ()
{    
 printf ("%d\n",add(2,4));
 system ("pause");
 return 0;
}

函数被 static 修饰时,使得这个函数只能在本源文件内使用,不能在其他源文件内使用。
#define 定义常量和宏
define 定义标识符常量
(#define MAX 500)
#define ADD(x,y) ((x)+(y)) //*后边 x+y 的括号很重要,且ADD和(x,y) 之间无空格
例子:

	   #define arr(x,y) x*y 
	   printf ("%d\n",arr(1+2,1+2);  //  输出为1+2*1+2=5 
	  【arr ((1+2),(1+2))   或 #define   arr(x,y) (x)*(y)//3*3=9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值