On 12/10/2017 16:18, Marko Rauhamaa wrote:
Grant Edwards <grant.b.edwa...@gmail.com>:
Using const with strings in C with amateurish libraries is a headache
because _some_people_ will write their declarations so as to require
pointers to mutable strings even when they have no intention of
mutating them. Those people should be hunted down and slapped with a
herring until they understand the error of their ways.
Hear, hear.
The standard library is much better about that.
You lost me there.
Seriously, though. C strings are not the most problematic issue. How
about other structures? What about:
long ftell(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
Should that be "const FILE *stream"?
In general, C record definitions (opaque structs) that represent
encapsulated classes don't take a "const" in any context. They *could*
but that isn't the tradition. For example, here's a random function from
the Linux kernel:
========================================================================
static bool tcp_fastopen_cookie_gen(struct request_sock *req,
struct sk_buff *syn,
struct tcp_fastopen_cookie *foc)
{
if (req->rsk_ops->family == AF_INET) {
const struct iphdr *iph = ip_hdr(syn);
__be32 path[4] = { iph->saddr, iph->daddr, 0, 0 };
return __tcp_fastopen_cookie_gen(path, foc);
}
#if IS_ENABLED(CONFIG_IPV6)
if (req->rsk_ops->family == AF_INET6) {
const struct ipv6hdr *ip6h = ipv6_hdr(syn);
struct tcp_fastopen_cookie tmp;
if (__tcp_fastopen_cookie_gen(&ip6h->saddr, &tmp)) {
struct in6_addr *buf = (struct in6_addr *) tmp.val;
int i;
for (i = 0; i < 4; i++)
buf->s6_addr32[i] ^= ip6h->daddr.s6_addr32[i];
return __tcp_fastopen_cookie_gen(buf, foc);
}
}
#endif
return false;
}
========================================================================
If you took a working C program and removed all the consts, it would
still work.
I don't think the language would miss them if they were to disappear.
It is anyway too crude a technique for the things people like to apply
it to.
>
> Note how both "req" and "syn" could well be declared as "const"
> pointers but are not.
const pointer, or pointer to const struct? Or both?
With a const struct, you are stopped from directly modifying elements,
but if an element is a pointer, nothing stops you writing to what the
pointer points to, unless that has a const target too. And then you've
going to have problems doing normal updates. This constness just
insinuates itself everywhere.
--
bartc
--
bartc
--
https://mail.python.org/mailman/listinfo/python-list