API : constness ?

Andrea Griffini agriff at tin.it
Tue Jun 1 14:22:53 EDT 2004


On Mon, 31 May 2004 23:36:38 -0700, Erik Max Francis <max at alcyone.com>
wrote:

>To his credit, he was talking about declaring an array of strings as
>const char *const.  That is, he was indeed making the data he was
>passing in truly const.  As others have pointed out, though, that
>doesn't guarantee that that data will be put in read-only memory, only
>that it makes it possible.

You can declare a constant pointer (you can't change
the pointer) to constant data (you can't change the
data). But still those properties are properties of
the pointer, not of the data. I know it may be
surprising at a first sight, but the code generated
by the compiler is not allowed to assume that the
"pointed to" data will not change; the reason is
that the limit of "you can't change the data" is
indeed just related to the pointer... in other words
the limit is only that you can't change the data

            ==> USING THAT POINTER <==

By no means you're stating the data is really constant.

Note also that casting away const-ness from a pointer
and changing the data is something that must be
supported if the data is not really constant.
In other words:

   void foo(const int *x)
   {
     int *y = (int *)x;
     ++(*y);
   }

   int main()
   {
     static int a = 3;
     foo(&a);
     // Here a will be 4
     ...
   }

The above code is perfectly legal; looking at main()
and at the declaration of foo the compiler cannot
decide to put "a" in read-only memory.

Declaring a parameter "const char *" is ONLY an help
for the programmer; it adds NO useful information for
an optimizer or code generator.
This at least was the original idea of constness...
I found myself in the quite blaspheme position of
even questioning if the const specification is an
help for the programmer or not; but this is a quite
unrelated topic.

Declaring a parameter "const char * const" is also
IMO nonsense; the passed (pointer) value is local
of the callee, changing it or not is not something
the caller should be interested about. It adds just
noise to the interface.

To recap in C and C++ a "const int *" is not a pointer
to a const int; an english description could probably
be "a pointer to an int that can't be used for writing"
(note that it says nothing about if what is pointed
to can be changed or not).

This looks quite OT for a python group, I'd suggest
the interested ones to ask for better explanations
in a C or C++ group about this topic.

HTH
Andrea



More information about the Python-list mailing list