高级会员
- 积分
- 797
- 金钱
- 797
- 注册时间
- 2017-5-21
- 在线时间
- 340 小时
|
const是用来定义常量的,在编译后应该是一个确定值的常量,并且在定义时应加上数据类型。而#defin则是用来做符号替换。
如:const int a=3;表示a的值为整型常量3.
#defin a 3表示你写的c或是h文件中的a会被3取代。
那么const怎样使用能更好的优化代码呢?
下面是STC的定时器例程:
/*------------------------------------------------------------------*/
/* --- STC MCU Limited ---------------------------------------------*/
/* --- STC89-90xx Series 16-bit Timer Demo -------------------------*/
/* --- Mobile: (86)13922805190 -------------------------------------*/
/* --- Fax: 86-0513-55012956,55012947,55012969 ---------------------*/
/* --- Tel: 86-0513-55012928,55012929,55012966----------------------*/
/* --- Web: www.STCMCU.com -----------------------------------------*/
/* --- Web: www.GXWMCU.com -----------------------------------------*/
/* If you want to use the program or the program referenced in the */
/* article, please specify in which data and procedures from STC */
/*------------------------------------------------------------------*/
#include "reg51.h"
typedef unsigned char BYTE;
typedef unsigned int WORD;
//-----------------------------------------------
/* define constants */
#define FOSC 11059200L
#define T1MS (65536-FOSC/12/1000) //1ms timer calculation method in 12T mode
/* define SFR */
sbit TEST_LED = P1^0; //work LED, flash once per second
/* define variables */
WORD count; //1000 times counter
//-----------------------------------------------
/* Timer0 interrupt routine */
void tm0_isr() interrupt 1 using 1
{
TL0 = T1MS; //reload timer0 low byte
TH0 = T1MS >> 8; //reload timer0 high byte
if (count-- == 0) //1ms * 1000 -> 1s
{
count = 1000; //reset counter
TEST_LED = ! TEST_LED; //work LED flash
}
}
//-----------------------------------------------
/* main program */
void main()
{
TMOD = 0x01; //set timer0 as mode1 (16-bit)
TL0 = T1MS; //initial timer0 low byte
TH0 = T1MS >> 8; //initial timer0 high byte
TR0 = 1; //timer0 start running
ET0 = 1; //enable timer0 interrupt
EA = 1; //open global interrupt switch
count = 0; //initial counter
while (1); //loop
}
编译后生成代码量:Program Size: data=19.0 xdata=0 code=79
但是这里面 T1MS 会被(65536-11059200L/12/1000)取代,这样虽然生成的代码量小,但程序运行过程中占用CPU时间很多,
我们更改一下代码,把代码改成如下:
/* define constants */
#define FOSC 11059200L
const int T1MS=(65536-FOSC/12/1000);
//#define T1MS (65536-FOSC/12/1000) //1ms timer calculation method in 12T mode
再生成的代码量:Program Size: data=21.0 xdata=0 code=216
我们再更改一下代码,把代码改成如下:
/* define constants */
#define FOSC 11059200L
const int T1MS=921;//(65536-FOSC/12/1000);
//#define T1MS (65536-FOSC/12/1000) //1ms timer calculation method in 12T mode
再生成的代码量:Program Size: data=21.0 xdata=0 code=216
证明T1MS在编译过程中已经把921给计算出来并将其代入程序内了。
这样的话T1MS就不会在程序里面再进行计算,从而减少了运行时间。
|
|