一、#define和const
#define:
1. 可以用来定义一个没有指定类型的常量,在定义的时候可以该对常量赋值;
2.也可以定义一个表达式,表达式可以带参数。
》》》》》》定义后不能被更改《《《《《《
用例一:
#define NUMBER 1000
用例二:
#define MAX(x,y) ((x)>(y)?(x):(y))
用例三:
#ifndef **
#define **
...
#endif
const:
可以定义一个有类型的变量,该变量一旦被定义就不能被修改。
const float A = 100.0;
二、条件编译
可在程序中减少要编译的程序。
#ifndef ***
#define ***
...
#elif ***
...
#endif
三、typedef
typedef并没有创建任何新类型,它只是为某个已存在的类型增加一个方便使用的标签。
用例一:
typedef unsigned char uch
uch a,b[10];
等同于
unsigned char a,b[10];
四、extern
声明extern关键字的全局变量和函数可以使得它们能够跨文件被访问。
#ifndef _A_H
#define _A_H
extern int number;
...
#endif
#include "A.h"
int number = 100;
void A(void)
{
...
}
#include "B"
#include "A"
void B(void)
{
int temp;
temp = number;
}
五、enum
方法1:
enum weekday
{
sun,
mou,
tue,
wed,
thu,
fri,
sat
};
enum weekday a,b,c;
方法2:
enum weekday
{
sun,
mou,
tue,
wed,
thu,
fri,
sat
}a,b,c;
方法3:
enum
{
sun,
mou,
tue,
wed,
thu,
fri,
sat
}a,b,c;
1.枚举是常量,不是变量,不能对其赋值,但可以在定义的时候赋值。
错误的写法:
sun = 7;
正确的写法:
enum weekday
{
sun = 7,
mou = 1,
tue,
wed,
thu,
fri,
sat
}a,b,c;
2.枚举元素的第一个值默认的是0,后面的元素的值是前一个元素值+1。
sun = 7,mou = 1,tue = 2,wed = 3,thu = 4,fri = 5,sat = 6
3.枚举元素不是字符也不是字符串,在使用的时候不能加单、双引号。
完整的用例:
#include <stdio.h>
enum weekday
{
sun,
mou,
tue,
wed,
thu,
fri,
sat
}a,b,c;
int main(void)
{
a = sun,b = mou,c = tue;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",c);
return 0;
}
显示结果:
0
1
2