const 限定符

版本新特性 / C89

// *** 以前 ***
//K&R C 没有 const:常量是没有类型的宏,
//没有任何机制阻止函数写入它只该读取的字符串
#define TAX_RATE 0.2

int countSpacesOld(text)
char *text;
{
    int n = 0;
    for (; *text != '\0'; text++)
        if (*text == ' ')          //像 *text = ' ' 这样的笔误能悄悄通过编译
            n++;
    return n;
}

char nameOld[] = "Ann Lee";
int spacesOld = countSpacesOld(nameOld);
double taxOld = 100 * TAX_RATE;
//spacesOld is 1
//taxOld is 20

printf("spacesOld is %d\n", spacesOld);
printf("taxOld is %g\n", taxOld);

// *** 在 C89 版本中 ***
//const 是一个承诺,编译器会确保它得到遵守
int countSpaces(const char *text) {
    int n = 0;
    for (; *text != '\0'; text++)
        if (*text == ' ')
            n++;
    //*text = ' ';    <- error: assignment of read-only location
    return n;
}

const double taxRate = 0.2;       //有类型的常量
//taxRate = 0.3;    <- error: assignment of read-only variable 'taxRate'

const char *name = "Ann Lee";
int spaces = countSpaces(name);
double tax = 100 * taxRate;
//spaces is 1
//tax is 20

printf("spaces is %d\n", spaces);
printf("tax is %g\n", tax);