osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Lies in education [was Re: The "loop and a half"]


Grant Edwards <grant.b.edwards at gmail.com>:

> I like [const qualifiers] in C because it allows the linker to place
> them in ROM with the code. It also _sometimes_ provides useful
> diagnostics when you pass a pointer to something which shouldn't be
> modified to something that is going to try to modify it.

Unfortunately, "const" is so tacky in practice that the language and the
standard libraries have rendered it useless.

One example is the surprising fact that string literals in C are "char
*" and not "const char *". Additionally, you can launder any constant
string into a nonconstant string with strstr(3):

    const char *cs = "hello";
    char *s = strstr(cs, "");
    s[0] = 'y';

Also, you'd expect execve(2) to take in:

    const char *const argv[]

Instead, it wants:

    char *const argv[]

which makes little semantic sense.

The reason for all of this weirdness is that the proper use of "const"
in C is very painful to do: you have to sprinkle your code with explicit
casts. Tons of legacy code would be riddled with compiler error
messages.

The solution was to pay lip service to "const." It would have been
better not to import "const" into the language.

(C++ has its own special issue with "const," which forced C++ to
introduce the ugly concept of const_cast<>().)


Marko