Квалификатор const

Изменения в новых версиях / C89

// *** before: ***
//K&R C had no const: a constant was a macro without a type, and
//nothing stopped a function from writing into a string it only reads
#define TAX_RATE 0.2

int countSpacesOld(text)
char *text;
{
    int n = 0;
    for (; *text != '\0'; text++)
        if (*text == ' ')          //a slip like *text = ' ' compiled silently
            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);

// *** in version C89: ***
//const is a promise, and the compiler holds you to it
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;       //a constant with a type
//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);