简体   繁体   English

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

[英]Why cast an unused function parameter value to void?

In some C project, I have seen this code:在一些 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;
}

Do the two casts to void serve any purpose?两个强制转换为 void 有什么用途吗?

这是为了避免编译器发出警告,因为某些参数未使用。

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.在原型中使用未使用的参数的原因通常是因为该函数需要符合某些外部 API - 也许它是一个库函数,或者指向该函数的指针被传递给另一个需要此调用约定的函数。 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:但是现在 GCC 会产生另一个警告:

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

This warning tells that the statement ud;这个警告告诉声明ud; , while being syntactically valid C, does not affect anything at all, and is possibly a mistake, not unlike the statement ,虽然在语法上是有效的 C,但根本不影响任何事情,并且可能是一个错误,与语句不同

abort;

which should perhaps have been written as abort();也许应该写成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.这就是(void)强制转换的用武之地 - 它会明确且明确地告诉编译器该语句应该完全没有任何效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM