Mark McIntyre said:
Interesting, though fairly annoying. I find that the vast bulk of
variables I declare are.
I'd be pretty surprised. Certainly its not my experience.
You may well be right; I haven't done any kind of in-depth study.
I'm fairly unconvinced that lack of constness makes code 'unsafe'.
Consider something like this:
char *s = "hello";
some_func(s);
If some_func() modified the string pointed to by s, the code is
unsafe. If s were a pointer to const char, this would be caught at
the point of the call.
I have to say, I can't see why one would want to have variables which
were by default not variable. Why not use constants for that?
I've added an "OT:" tag to the subject header. If this discussion
continues, we might want to take it to comp.lang.misc.
It's an idea I had some years ago in the context of a different
language, one that's more flexible than C in how objects can be
initialized (Ada).
In Ada, there are two kinds of objects: variables and constants.
Objects are the same as in C. Constants are objects declared with the
"constant" keyword, much like "const" in C. Variables are
non-constant objects.
My experience in Ada was that objects very commonly were initialized
to some desired value, and that value was never changed over the
lifetime of the object. I tried to declare objects with "constant"
whenever possible, giving a hint both to the compiler and to the
reader that they weren't going to change after the initial
declaration. My vague impression was that this was the case more
often than not, and that making objects constant by default might be
an improvement.
This may be less true for C than for Ada, for various reasons.
If I see a reference to an object, I can look at its declaration to
get more information about it. If it's declared const, I know that
the value at the point of reference is the same as the value in the
initializer. If it isn't, I have to understand the execution of the
program to figure out whether it might have been modified (and so does
the compiler, but that's a secondary issue).
Here's a trivial example: a swap routine:
void swap_int(int *x, int *y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
tmp is never modified after its initialization, but how many C
programmers would bother to declare it const?
In general, I tend to think that making the default more restrictive,
while allowing it to be relaxed explicitly, tends to make for cleaner
and safer code. YMMV.
To return to something vaguely approaching topicality, I suppose I'm
advocating more use of "const" for objects that don't change after
they're initialized.