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


Hi!

I'm definitely no expert on C programming, so I hope I know what I'm
replying here! ;)

> I'm not quite certain, but I think you are confusing what is constant
> here.  arg IS read-only -- it isn't affected by anything you do to *arg.
> int *arg means arg contains an address; in your example, the address of
> the variable "var", and *arg is a reference to its contents.  var exists
> in the local memory space of main. When you pass its address to f as
> "const int *arg", you promise not to to do something like:
> 
> int f (const int *arg)
>   {
>   int my_var;
>   arg = &myvar;
>   if (*arg > 5) *arg -= 5;
>   return *arg+2;
>   }
>
> (reassign a new value to arg) or
> 
> int f (const int *arg)
>   {
>   if (*arg > 5) arg++;
>   return *arg+2;
>   }
> 
> (increment arg so that it points at the next int location in memory
> contiguous to var, whereever that might be and whether or not you own
> it).

I don't think that's what it means. In example,

int f (const int *arg)
  {
  arg++;
  }

is perfectly valid from the compiler point of view (and an obvious
nonsense from the programmer point of view), but:

int f (const int *arg)
  {
  (*arg)++;
  }

is not valid. The address is *not* read-only, but the value is. To be
sure, I asked on comp.lang.c and people agreed.

> The compiler will almost certainly not complain about:
> 
> int f (const int *arg)
>   {
>   int *my_arg;
>   my_arg = arg;
>   if (*my_arg > 5) *my_arg -= 5;
>   return *my_arg+2;
>   }

It will complain, because you have to cast arg to (int *), i.e.

  int *my_arg = (int *) arg;

Otherwise you're discarding the const qualifier.

> If I'm wrong about any of this I'd love to know about it.

I *think* you are, but you should definitely get second opinion! O;)

Best wishes,

Andrej


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