| Re: [AD] Update on `const' | 
[ Thread Index | Date Index | More lists.liballeg.org/allegro-developers Archives ]
In reply to Hein Zelle <hein@xxxxxxxxxx>:
[snip - just use `const']
>Even if this is true, is it worth converting back to 'const'? The fact
>that we switched in the first place means that preprocessor trickery
>with 'const' is not too easy, and using AL_CONST makes it almost
>trivial. What's the gain?
Well, what about if I wrote:
#define INTEGER int
and used that everywhere. It would soon get very annoying, especially if
somebody else was reading/copying my code. I just think it would be
better to use the proper `const' keyword rather than use the roundabout
AL_CONST macro.
>> char* get_filename(char* path);
>> const char* get_filename_const(const char* path);
>
>Ugh? what's wrong with 
>
>char *get_foo(char const * path); ?
Its semantics are totally wrong: it takes a pointer to constant data,
and returns a pointer to mutable data. Consider a situation where that
constant data is actually stored in ROM, but somebody thinks s/he can
write to it. More likely, the compiler optimises some surrounding code
on the assumption that the string won't be changed, when in fact it
will.
>It means (AFAIK) exactly what you say: the parameter is not altered,
>and the return value may be altered.
No, it means that the parameter is readonly, but that we return a
writeable pointer into readonly memory (which is plain wrong).
>In C++ the function probably wouldn't compile as it is now,
>since it assigns a const string to a non-const pointer.
This issue has nothing to do with C vs C++.
>I think in this case we should just make the return value of
>get_filename be const.
Great! Except this case:
{
  char buf[1000];
  file_select_ex("Message", buf, sizeof(buf), 0, 0);
  *get_filename(buf) = 0; // this is valid C++, don't know about C
}
  The function call is valid (it is OK to pass a `char*' to a function
  expecting a `const char*'), but the assignment is not.
> Are there any examples where it is really
>useful to split this up in 2 functions? It seems awkward to me.
The above example needs a prototype:
  char* get_filename(char*);
but there are situations (often, though not always, when dealing with
C++ strings) where you want to use a `const' pointer. This is needed
when dealing with ROM, and nice when dealing with compiler
optimisations.
Bye for now,
-- 
Laurence Withers, lwithers@xxxxxxxxxx
                http://www.lwithers.demon.co.uk/
Attachment:
signature.asc
Description: PGP signature
| Mail converted by MHonArc 2.6.19+ | http://listengine.tuxfamily.org/ |