bug-gnulib
[Top][All Lists]
Advanced

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

Re: const local variables


From: Jim Meyering
Subject: Re: const local variables
Date: Sun, 11 Apr 2010 18:49:26 +0200

James Youngman wrote:
> On Sun, Apr 11, 2010 at 1:08 PM, Bruno Haible <address@hidden> wrote:
>> James Youngman wrote:
>>> * lib/close-stream.c (close_stream): Make boolean variables const
>>> to document the fact that we set but do not change them.
>>> --- a/lib/close-stream.c
>>> +++ b/lib/close-stream.c
>>> @@ -55,9 +55,9 @@
>>>  int
>>>  close_stream (FILE *stream)
>>>  {
>>> -  bool some_pending = (__fpending (stream) != 0);
>>> -  bool prev_fail = (ferror (stream) != 0);
>>> -  bool fclose_fail = (fclose (stream) != 0);
>>> +  const bool some_pending = (__fpending (stream) != 0);
>>> +  const bool prev_fail = (ferror (stream) != 0);
>>> +  const bool fclose_fail = (fclose (stream) != 0);
>>
>> There are programming languages where this style of using 'const' may
>> be customary (like C++ or Java), but I don't think it helps in C code:
>>  1) For the person reading the code, it draws the attention away from
>>     more importants parts of the code.
>
> On the contrary, it's a signal that there is no need to consider
> changes to the values of those variables in the later code.

While "const" on a pointer is even more useful,
I do find the "const" annotation to be useful also on scalars.

When we declare a pointer to be const, it protects the careless maintainer
from directly modifying anything through that pointer, as well as from
using it as an argument to a function that expects a non-const parameter
in that position.  With a const scalar, we get only the first.

The "const"-on-a-scalar also improves readability, by declaring the
intent of the author.
Even if you use an IDE with enough static analysis smarts to derive
that a scalar is currently constant, that is not the same, and may
not reflect #ifdef'd code that *does* modify it.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]