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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4647665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:30:36  来源:igfitidea点击:

Why cast an unused function parameter value to void?

ccastingvoid

提问by bastibe

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 有什么用途吗?

采纳答案by Benoit Thiery

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

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

回答by Antti Haapala

The reason for having unusedparameters 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.

在原型中有未使用的参数的原因通常是因为该函数需要符合某些外部 API - 也许它是一个库函数,或者指向该函数的指针被传递给另一个需要此调用约定的函数。然而,并非调用约定使用的所有参数都在函数本身中实际需要。

The reason for mentioningthe 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 warningcan 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 anotherwarning:

此警告现已取消。但是现在 GCC 会产生另一个警告:

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

Thiswarning 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

警告表明该语句ud;虽然在语法上是有效的 C,但根本不会影响任何事情,并且可能是一个错误,与该语句不同

abort;

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

也许应该写成abort();它来做某事。

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)演员表的用武之地——它会明确地告诉编译器该语句应该完全没有效果。