Here's a bit of an explanation of why I const like I do:
http://xoa.petdance.com/Use_const_proactively
One of my jobs in Perl 5 and Parrot has been to apply const as much
as humanly possible.
== Const your local variables
The following is adapted from C++ Coding Standards by Herb Sutter and
Andrei Alexandrescu (with some C++-specific stuff removed):
const is your friend: Immutable values are easier to understand,
track, and reason about, so prefer consted variables wherever it is
sensible and make const your default choice when you define a value.
It's safe, and it's checked at compile time. Don't cast away const
except to call a const-incorrect function. Constants simplify code
because you only have to look at where the constant is defined to
know its value everywhere. Consider this code:
void Fun( const char * p ) {
const size_t len = p;
/* ... 30 more lines ... */
}
When seeing len's definition above, you gain instance confidence
about len's semantics throughout its scope. It's a snapshot of p's
length at a specific point. Just by looking up one line, you know
len's semantics over its whole scope. Without the const, len might be
later modified. Best of all, the compiler will help you ensure that
this truth remains true.
Yes, const is viral -- add it in one place, and it wants to
propagate throughout your code as you call other functions who
signatures aren't yet const-correct. This is a feature, and this
quality greatly increases const's power.
Const-correctness is worthwhile, proven, effective, and highly
recommended. Understanding how and where a program's state changes is
vital, and const documents that directly in code where the compiler
can help to enforce it.
== Const your function parameters
Consting function parameters also lets the compiler know the behavior
of your function. Consider this snippet of code:
char buffer[20];
c = buffer[0];
The compiler or lint can now warn you that you're using buffer even
though it hasn't been initialized. But what about this:
void foo(char *p);
char buffer[20];
foo(buffer);
c = buffer[0];
Is foo() initializing what is sent into it? The compiler can't tell.
But if you define it like so:
void foo(const char *p);
now the compiler knows that buffer can't be getting initialized.
Think of consting your function parameters as a very basic contract
with the caller.
--
Andy Lester => [EMAIL PROTECTED] => www.petdance.com => AIM:petdance