In <Xns93A8289E3231whitesuneapollolv@130.133.1.4> Peteris Krumins <> writes:
> It's not clear enough for me when to use const and when not use const.
When writing a complete application, never.
When writing a library that may be used by other people, in every function
parameter declaration where it makes sense.
These guidelines will minimise the headaches caused by const.
>it make? If i precisely declare variables const where needed does the
>compiler do it's job better?
>
> For example,
> int function(const char *data, int section) {
> ...
> }
>
> What's the difference if i had simply 'char *data' and not 'const char
>*data'?
Here's a simple program showing the difference:
fangorn:~/tmp 147> cat test.c
#include <string.h>
void mmemcpy(void *dest, void *src, size_t size)
{
memcpy(dest, src, size);
}
int main()
{
const float f = 1.75;
float g;
memcpy(&g, &f, sizeof f);
mmemcpy(&g, &f, sizeof f);
return 0;
}
fangorn:~/tmp 148> gcc test.c
test.c: In function `main':
test.c:14: warning: passing arg 2 of `mmemcpy' discards qualifiers from pointer target type
Note that memcpy declares its second parameter as having the type const
void *. This way, the function can be called with arguments that are
pointers to both const and non-const objects. By omitting const from
the definition of mmemcpy, I restrict it to taking only pointers to
non-const objects as arguments (for no redeeming benefits).
Of course, if you never use const in your program, this is a non issue.
Hence the guidelines at the beginning of my post.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: