This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: const warning...
- From: Fergus Henderson <fjh at cs dot mu dot OZ dot AU>
- To: Robert Dewar <dewar at gnat dot com>
- Cc: Theodore dot Papadopoulo at sophia dot inria dot fr, gcc at gcc dot gnu dot org
- Date: Sat, 5 Jul 2003 16:31:33 +1000
- Subject: Re: const warning...
- References: <20030705053540.C46ACF2CAE@nile.gnat.com>
On 05-Jul-2003, Robert Dewar <dewar@gnat.com> wrote:
> > Adding "const" on local variable definitions that happen to only be set
> > once is not especially useful for documentation or maintenance purposes.
>
> I disagree strongly. The difference between constants and variables is
> important and fundamental.
Well, yes and no. Sometimes it is important, but other times it is not.
I agree that it can be useful, I just don't think that it is especially
useful, and sometimes the advantage of the extra information can be
outweighed by the distracting noise factor of the explicit "const"
declaration in C/C++.
Whether or not a variable can be declared "const" can depend on where
the variable is declared. Consider for example
void print_squares(void) {
int i;
int sqr_i;
for (i = 0; i < 10; i++) {
sqr_i = i * i;
printf("%d squared is %d\n", i, sqr_i);
}
}
versus
void print_squares(void) {
int i;
for (i = 0; i < 10; i++) {
const int sqr_i = i * i;
printf("%d squared is %d\n", i, sqr_i);
}
}
If you are arguing that there is a fundamental and important difference
between these two code snippets, then I would beg to differ. There is
a difference, certainly, but I don't find it especially important.
While I agree that it is better style to declare variables in their
closest enclosing scope, I wouldn't say that it makes such a *fundamental*
difference to the code if you instead declare them at the top of the function.
> One of the problems with C++ (and Ada for
> that matter) is that they require extra syntax for constants which tends
> to encourage the use of variables by default.
I agree with you about the language design issue.
But in C/C++, I find that the noise factor from declaring every
unchanging parameter or local variable "const" is quite large,
especially since most C/C++ programs are not written this way.
In Ada it is not so bad since parameters can't be assigned to
(i.e. they are always implicitly const or const reference).
--
Fergus Henderson <fjh@cs.mu.oz.au> | "I have always known that the pursuit
The University of Melbourne | of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh> | -- the last words of T. S. Garp.