From: <do...@sm...> - 2002-09-12 07:03:45
|
> > "const xine_t *const xine" is best read from right to left: xine is a > > constant pointer to a xine_t constant. So the very left const says: You > > are not allowed to write into this structure, because it's constant. > > The *const says: This pointer is constant, do not make it point > > elsewhere. > > what's the point in the second one? Optimization and rule enforcement. You're telling the compiler explicitly that this value will never change; so the optimizer doesn't have to work that out on its own. And the compiler will emit some sort of diagnostic if someone inadvertantly does try to change it. Granted, I haven't paid close attention to the const thread; but just as a data point here's how I normally use const with functions: /* declaration */ int somefunc(const char*,int); /* definition */ int somefunc(const char* const arg1,int const arg2) { ... } Arrays/strings that won't be modified are made const in the declaration. As someone else mentioned, this is useful for someone to know when they _call_ this function, because it tells them that they don't have to worry about the function modifying the array contents. Within the function itself this helps ensure that the array isn't ever used accidentally in some non-const way. I normally make all of the arguments to my functions const in the definition, mainly because I consider modifying argument variables within a function to be bad style :-). As mentioned above, this tells the compiler explicitly that they won't be changed, and helps the compiler spot accidental assignments to those variables. Note that this works fine with pointers that are intended to return a value: int otherfunc(int* const retp) { ... *retp=somevalue; } because the const in this case just makes sure that the pointer still points to the same return location that the caller chose; it doesn't stop the function from storing a value _at_ that location. Within a function, local variables will be made const whenever it's easy and practical. This lets me use lots of meaningful variable names, while making it as easy as possible for the compiler to optimize them out of existence in the object code. Now, from skimming this discussion it sounds like it has to do with declaring a const _return_ value for a function. I rarely, if ever, use const on a return value -- mainly because I'd have to pull out the C standard every time I called the function just to remind myself exactly what the const will mean in that context :-) -Dave Dodge/do...@sm... |