Lies in education [was Re: The "loop and a half"]

Marko Rauhamaa marko at pacujo.net
Thu Oct 12 11:18:44 EDT 2017


Grant Edwards <grant.b.edwards at 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;
}
========================================================================

Note how both "req" and "syn" could well be declared as "const" pointers
but are not.


Marko



More information about the Python-list mailing list