Re: [xml] what should to be 'const'?



massimo morara wrote:
On Mon, May 21, 2007 at 10:00:03AM -0700, Rush Manbert wrote:

massimo morara wrote:

In the function xmlCopyNode(const xmlNodePtr node, int extended) [tree.c], what is supposed be 'const'?



Write the declaration out, then read it backwards to determine what is const. In this case, I believe the declaration would be "const xmlNode *", so reading it backward says that it's a pointer to a xmlNode that is const. A const pointer would be "xmlNodePtr const node"


        Sorry, but i'm pretty sure that "const xmlNodePtr node" is (in
"tree.h") "xmlNode * const node", so is the pointer that is costant;
next i transcribe a little trivial program to verify a similar case.
        My question is: what we wish costant: the pointer or the data?
        If we wish that is costant the structure pointed, we should
write "xmlNode const * node" or, defining in "tree.h" something like

typedef  xmlNode const *  xmlConstNodePtr;

write "xmlConstNodePtr node".
        For xmlCopyNode() and for other functions.

                massimo morara


ps: sorry for my bad english


---- test program ----

#include <stdio.h>

typedef struct
 {
   int foo;
 } fooStruct ;


typedef  fooStruct *  fooStrPtr;


void  changeFooData (const fooStrPtr  pfd)
 {
   pfd->foo = 2;

   /* pfd++; forbidden */
 }


int main (void)
 {
   fooStruct  fooData;

   fooData.foo = 1;

   changeFooData(&fooData);

   printf("foo val: %i\n", fooData.foo);

   return(0);
 }

Massimo,

Sorry, my mistake. I thought that "const xmlNodePtr node" meant the same thing as "const xmlNode * node", as if xmlNodePtr were a macro definition that expanded to "xmlNode *", but the typedef changes things, so the const modifies the pointer itself.

I took your example and changed changeFooData to this:

void  changeFooData (const fooStruct *  pfd)
{
        pfd->foo = 2; /* <--- Forbidden */
        
        pfd++;
}

and the compiler complains about the assignment, but not the increment, so now it makes sense to me.

You are correct and I have learned something. The declaration means that the pointer is const, not the data. If what you are asking for is the intent, then Daniel will need to answer.

- Rush



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