This is the mail archive of the gsl-discuss@sources.redhat.com mailing list for the GSL 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: Parameter vectors declared as const in minimized functions


On Tue, 4 Jan 2005 17:00:53 -0500 (EST)
"Robert G. Brown" <rgb@phy.duke.edu> wrote:

> That is, I think that the order of precedence is const (int *arg) (the
> integer pointer itself cannot change to point to some other value),
> not const int (*arg) (the contents of memory pointed to by *arg cannot
> change).
> 

Even if I'm definitely not an expert programmer, let me try to give my
little contribution to the discussion. I think the sentence above is the
origin of the misunderstanding. Indeed a declaration

const int *arg

is interpreted as

cost int (* arg)

that is a pointer to a constant integer. The content of the memory
location addressed by the pointer, i.e. the integer, is the constant,
not the memory address stored in pointer arg. To make the pointer
itself constant, you need a

int * const arg

which is interpreted, so to speak, as

int (* const arg)

that is a constant pointer to an integer. In this case, the integer
content of the memory address can be changed, but the memory address
pointed by arg cannot. 

In other words, this code

---------- BEGIN OF CODE ----------
int test1(const int * arg)
{
  arg=arg+1;
  arg=arg-1;
  return(*arg);
}

int test2(int * const arg)
{
  *arg=*arg+1;
  *arg=*arg-1;
  return(*arg);
}


int main()
{
  int val=1;
  test1(&val);
  test2(&val);
  return 0;
}
---------- END OF CODE --------------

will compile without warnings.

Of course, you can make things really sticky with a

const int * const arg

Look at page 216 of Kernigham and Ritchie (I know, nobody usually read
this part) for an authoritative example.

	G.

-- 
Giulio Bottazzi                 PGP Key ID:BAB0A33F 

Attachment: pgp00000.pgp
Description: PGP signature


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