109

In some C project, I have seen this code:

static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
    (void)ud;
    (void)osize;
    /* some code not using `ud` or `osize` */
    return ptr;
}

Do the two casts to void serve any purpose?

bastibe
  • 16,551
  • 28
  • 95
  • 126

2 Answers2

103

It is there to avoid warnings from the compiler because some parameters are unused.

Benoit Thiery
  • 6,325
  • 4
  • 22
  • 28
  • 3
    What is the best way to suppress the warnings: http://stackoverflow.com/questions/3417837/what-is-the-best-way-to-supress-unused-variable-x-warning – Ciro Santilli OurBigBook.com Sep 17 '14 at 07:12
  • 1
    @Benoit what does casting to void actually do? Is its only function to show the compiler that you're intentionally ignoring something or does (void) actually do something and when the compiler sees it, it'll just count it as having done something with the variable and therefore not issue a warning? – Tan Wang Sep 15 '16 at 14:20
  • 3
    @TanWang Its only function is to show the compiler that you're intentionally ignoring something. It will not do anything at runtime. – zwol Sep 27 '16 at 20:23
  • Anyone knows where this is documented? Language specyfication? Compiler manual? Does it have a name (such statement)? – Kamil Feb 13 '22 at 23:26
17

The reason for having unused parameters in the prototype is usually because the function needs to conform to some external API - perhaps it is a library function, or a pointer to that function is passed to another function that expects this calling convention. However not all arguments used by the calling convention are actually needed in the function itself.

The reason for mentioning the parameter name in the body is to avoid warnings like

unused.c: In function ‘l_alloc’:
unused.c:3:22: warning: unused parameter ‘ud’ [-Wunused-parameter]
 void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
                      ^~

This warning can be suppressed with using the actual parameter in the function body. For example if you do have the following statement:

ud;

This warning is now suppressed. However now GCC will produce another warning:

unused.c:5:5: warning: statement with no effect [-Wunused-value]
     ud;
     ^~

This warning tells that the statement ud;, while being syntactically valid C, does not affect anything at all, and is possibly a mistake, not unlike the statement

abort;

which should perhaps have been written as abort(); instead for it to do something.

And that's where the (void) cast comes in - it will tell the compiler unambiguously and explicitly that the statement is supposed to have absolutely no effect at all.