Willy,

Am 05.03.20 um 19:40 schrieb Willy Tarreau:
> Don't worry, it's not a matter of C experience or whatever. C isn't trivial
> and we all have doubts about plenty of things. Some people put tons of
> parenthesis because operators precedence is never obvious, others have
> trouble with const, others with many other things. And in the end they
> still produce good code that runs the whole internet because they're
> careful.
> 
> Regarding the "const" thing, I can give you a few hints if that helps.
> The first one is to remember that when you write:
> 
>     type *pointer;
> 
> it means "*pointer is of type <type>" thus "pointer is a pointer to an
> area of type <type>". So when you write "const char *pointer", then
> "pointer is a pointer to an area of const char".

Yeah, I technically know this, but `const char *` reads to me like
"const (char pointer)" not "(const char) pointer" :-)

> Another way to remind it is that when you write strings in your code
> like:
> 
>      p = "alalafred";
> 
> Then this string in quotes is a const. And it's for this that you
> generally want to place "const char *" in front of the argument of a
> function that it supposed to support such an argument which must not
> be modified. Thus strlen() takes a const char *, in order to be
> compatible with this.

Yes, the bit about const chars makes sense. I guess I can remember that
(I hope).

> One tricky area is related to allocations. You could think that it'd
> be fine to set the return of an strdup() to "const char*" because you
> don't need to modify it. But there's a catch. Whatever is before or
> after the area belongs to the area, and free() will need to modify
> some hidden pointers around this, or even inside the area. Thus free()
> cannot take a "const void*", and it will need a "void*". For this
> reason, when you copy the result of an strdup() into a variable that
> you don't intend to modify, you still need to declare it as a pointer
> to a writable area just so that free() can be called on it upon exit.

Oh, this is good to know. I wasn't aware of that.

Thanks
Tim Düsterhus

Reply via email to