Hacker News new | ask | show | jobs
by trealira 617 days ago
I was more referring to how, in the K&R example, a function of type "int (*)(char *, char *)" is cast to "int (*)(void *, void *)", in contradiction to what they said here:

> Before someone mentions qsort(): the comparator function really is supposed to take a void*, and inside the function, you re-cast the void* argument to a pointer type of your desire. If you don't do it in that order, you're using it wrong.

In contrast, the K&R example is an example of explicitly undefined behavior in the C standard:

The behavior is undefined in the following circumstances:

- A pointer is used to call a function whose type is not compatible with the pointed-to type (6.3.2.3).

2 comments

> the K&R example is an example of explicitly undefined behavior in the C standard

You can’t blame K&R C for that. It predates “the C standard” by over a decade (1978 vs 1989)

When it was written, what K&R said was C.

The second edition was released in 1988, and it was based on a draft of the first ANSI C standard, and even then, the line stating that this was undefined behavior was already present.

http://jfxpt.com/library/c89-draft.html#A.6.2

> A pointer to a function is converted to point to a function of a different type and used to call a function of a type not compatible with the original type (3.3.4).

The example is still the same in the second edition of K&R, which is based on C89.
Ah, I missed that. However, footnote 41 states “The same representation and alignment requirements are meant to imply interchangeability as arguments to functions […]”, which could be taken as implying compatibility of function types, though the normative wording doesn’t directly support that.
Good point. It would be nice if the C standard were slightly clearer here.