Also note you really should mark a and b const, too. It allows the compiler to optimize code more aggressively, but it also helps you catch programming errors -- say, if in a later version you tried to modify something pointed by a or b. Because you cast it to a non-const type, the compiler will allow it, but the users of the function would assume otherwise because the content at ap and bp is marked const. (With aggressive optimization, the compiler may trust the declaration, and assume the values are not changed. This may result in very strange behaviour, very difficult bugs to pinpoint.)
Since you already realized the problem, let me push you a bit further. This is how you really should write the function:
Code:
static int cmp_move(const void *const ap, const void *const bp)
{
const struct move *const a = (const struct move *const)ap;
const struct move *const b = (const struct move *const)bp;
if (a->prescore < b->prescore) return -1;
if (a->prescore > b->prescore) return 1;
return a->move - b->move;
}
The above version adds the const qualifier to ap and bp, to a and b, and to data pointed to by a and b.
Here's the three lines that help me get the const qualifiers right:
Code:
const char *s = ...; /* Data pointed to by s is constant. s++ is allowed, s[0]++ is not allowed. */
char *const s = ...; /* Pointer s is constant. s++ is not allowed, s[0]++ is allowed. */
const char *const s = ...; /* Pointer s and the data it points to are both constant. Neither s++ nor s[0]++ is allowed. */
Hope this helps you write better code,
Nominal Animal