Why cast an unused function parameter value to void?

别说谁变了你拦得住时间么 提交于 2019-11-26 01:42:52

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4647665/why-cast-an-unused-function-parameter-value-to-void

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!