This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Const warning? (was: Re: [Patch] More redundant...)


<<attribution snipped:>>
> > I thinking about a warning for variables which the compiler can see
> > are not modified. Something like:
> >
> > Warning: Variable x should be const.

This is easy for scalars (parameters or locals), but hard for array and struct/union types.
This is too bad, because such a message probably would prevent several bugs per programmer
per year.  Extensive use of 'const' is very beneficial for maintenance and documentation.
It's amazing how helpful it is to see lots of 'const': if it compiles, then the compiler
has told you that the value does not vary in time, so you don't have to check.

A couple years ago I got fairly far along on this, starting with gcc-2.96.  The message
I chose was "warning: const omitted".  There was a bit available in the type word
(the next-to-last unused bit), and I used that.  Then you just look at all places that
the compiler would complain about using as an lvalue something that is declared const,
and mark the type as non-const instead.  Increment/decrement required some fiddling,
as did taking the address of an object.  At the end of each scope, then walk the
declarations and complain for those objects that are not marked as non-const,
and also not marked as const.

This worked quite well for a while [the number of warnings is large], but then
I discovered the fundamental problem with the type system in 2.96.  The existing type
system in 2.96 has the property that, after declaration is finished, then the type word
itself is a constant, and can be freely copied (passed as a parameter, etc.),
indirected (have '*' applied to it), and selected (have '.member' applied to it).
But for non-const marking in one pass, all the non-zero non-const bits must be
forwarded to the "master" copy for the expression [object], and doing so is
difficult.  So I gave up.

Side note: The prefered syntax ought to be "char const *foo;" instead of
"const char *foo;".  Why?  Because then there is a simple rule for where 'const'
may appear in a declaration: immediately to the left of every identifier, and
immediately to the left of every '*'.  So the "maximal const" form in this case
is "char const *const foo;".

--
John Reiser, jreiser at BitWagon dot com


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]