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

发布于 2024-10-11 20:52:01 字数 278 浏览 2 评论 0原文

在一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终难愈 2024-10-18 20:52:01

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

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

淡淡の花香 2024-10-18 20:52:01

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

在函数体中提及参数名称的原因是为了避免出现诸如

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) {
                      ^~

此警告可以通过在函数体中使用实际参数来抑制的警告。例如,如果您确实有以下语句:

ud;

此警告现已被抑制。然而,现在 GCC 将产生另一个警告:

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

这个警告告诉我们,语句 ud; 虽然在语法上是有效的 C,但根本不会影响任何内容 语句不同,

abort;

,并且可能是一个错误,与应该写成 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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文