[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: const local variables
From: |
James Youngman |
Subject: |
Re: const local variables |
Date: |
Sun, 11 Apr 2010 13:29:07 +0100 |
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.
> 2) For the person modifying the code, it requires additional attention,
> to remember to remove 'const' here and there. That's frequent in C,
> because the vast majority of code in C is written in style that
> modifies local variables (as opposed to functional style).
This statement is true but I don't understand its relevance. If some
of the variables are modified and some are not, this surely increases
the value of the const qualifier as an item of documentation.
> If you find yourself looking at a function where you don't overlook
> all the uses of a variable, then my advice would be to
> a) use an IDE which shows you all uses of a local variable on
> demand (Eclipse can do that, and José Marchesi knows how to do
> that with Emacs),
> b) limit the scope of the variables. Create intermediate blocks
> that declare variables for the minimum possible scope.
>
> Bruno
>
- [PATCH] Don't error out if stdin/stdout/stderr was already closed., James Youngman, 2010/04/11
- Re: [PATCH] Don't error out if stdin/stdout/stderr was already closed., Jim Meyering, 2010/04/11
- Re: const local variables, Bruno Haible, 2010/04/11
- Re: const local variables,
James Youngman <=
- Re: const local variables, Jim Meyering, 2010/04/11
- Re: const local variables, Paul Eggert, 2010/04/11
- "const" scalars, Jim Meyering, 2010/04/12
- Re: "const" scalars, Ben Pfaff, 2010/04/12
- Re: "const" scalars, Jim Meyering, 2010/04/12
- Re: "const" scalars, Paul Eggert, 2010/04/12
- Re: const local variables, Ludovic Courtès, 2010/04/12