Martin Valgur Martin Valgur - 2 months ago 6
C Question

Purpose of casting a struct pointer to void without using the result

I am trying to make sense of the following bit of C code.

static unsigned
parent(const struct binheap *bh, unsigned u)
{
(void)bh;
return (u / 2);
}


What could the purpose of
(void)bh;
be? It is not assigned to anything and should not have an effect on the output. The only purpose I can think of might be as a kind of an assert against a null pointer perhaps.

For context, that snippet is from the original implementation of a B-heap. That code tends to be rather too clever in other places as well, e.g. doing
for (unsigned n = 2; n; n += n) {
to break at n = 65535.

Answer

(void)bh; has no effect in the generated code. However, with many compilers it will prevent the compiler from issuing a warning about the parameter bh not being otherwise used in the function, and that was almost certainly the intent of the programmer. bh being a struct pointer is irrelevant; if this technique works at all, it will work regardless of the type of the unused parameter.

C++ has a more elegant way to accomplish this, allowing you to omit the variable name for any argument you don't need --

static unsigned
parent(const struct binheap *, unsigned u)
{
     return (u / 2);
}

-- but C doesn't support this. Some compilers have extensions for the same purpose that are, if not so elegant, at least more self-describing, e.g. GCC's

static unsigned
parent(const struct binheap *bh __attribute__((unused)), unsigned u)
{
     return (u / 2);
}

The (void)bh; trick is the only technique for suppressing unused-parameter warnings that uses only the facilities of ISO C; on the other hand, it's not guaranteed to work, the warnings a compiler emits are entirely up to that compiler, so you're already in implementation-defined territory no matter what you do.