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, Jan 04, 2005 at 11:15:46PM +0100, Andrej Prsa was heard to remark:
> Hi!
> 
> > int f (const int *arg)
> >   {
> >   if (*arg > 5) arg++;
> >   return *arg+2;
> >   }

The above is perfectly valid c code.  'arg' is a local variable;
you can add to it as you wish.  You cannot affect the behaviour
of other unrelated parts of the program by
adding/subtracing/multiplying arg.

> int f (const int *arg)
>   {
>   arg++;
>   }
> 
> is perfectly valid from the compiler point of view 

Yep.

> 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.

yes.  This is a clear violation of const-ness.

> 
> > The compiler will almost certainly not complain about:

wrong.

> > int f (const int *arg)
> >   {
> >   int *my_arg;
> >   my_arg = arg;
> >   if (*my_arg > 5) *my_arg -= 5;
> >   return *my_arg+2;
> >   }

This is very wrong, you are violating the const'ness of the array.
Compilers can do optimizations based on the assumed constness of 
things; by violating it in this way, you will get bizarre and 
invalid results, depending on the optimizations taken.

As an extreme example, the compiler might have optimized a call
to f out of a loop, because it may have perceived f to be a leaf
with no effects.  In other words, if calling f() always returns the same
value, **and it has no other side effects**, why call it over and over? 
Compilers these days are smart enough to make deductions like this.

By voilating const-ness, you've given it a side-effect it would not
otherwise have had.

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

sort of ...

>   int *my_arg = (int *) arg;

yes, you can cast-away const'ness in this fashion.  Because its an
explicit cast, the compiler will *not* complain, becuase it assume 
you knew what your were doing when you performed the cast.  A cast
is like saying "yes, Im really really sure".  However, its usually
a bad thing to do.

--linas


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