为什么将未使用的函数参数值转换为 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;
}
Do the twocasts to void attend for any Purpose?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是为了避免编译器因某些参数未使用而发出警告。
It is there to avoid warnings from the compiler because some parameters are unused.
原型中具有未使用参数的原因通常是因为该函数需要符合某些外部 API - 也许它是一个库函数,或者指向该函数的指针被传递给另一个需要此参数的函数调用约定。然而,并非调用约定使用的所有参数在函数本身中实际上都需要。
在函数体中提及参数名称的原因是为了避免出现诸如
此警告可以通过在函数体中使用实际参数来抑制的警告。例如,如果您确实有以下语句:
此警告现已被抑制。然而,现在 GCC 将产生另一个警告:
这个警告告诉我们,语句 ud; 虽然在语法上是有效的 C,但根本不会影响任何内容 语句不同,
,并且可能是一个错误,与应该写成
abort();
的而不是让它做某事。这就是
(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. 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
This warning can be suppressed with using the actual parameter in the function body. For example if you do have the following statement:
This warning is now suppressed. However now GCC will produce another warning:
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 statementwhich 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.