为什么要将未使用的函数参数值强制转换为 void?

在一些 C 项目中,我看到过这样的代码:

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;
}

这两个无效的石膏有什么用吗?

29155 次浏览

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

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.