对于未使用的参数,什么是“更好的”:(x=x)或(void(x))?

好吧,我们都知道有时我们会获取函数的参数,但我们并没有真正使用它们。

我们不想得到任何编译器警告,所以我们需要以某种方式“使用”但不真正使用这些参数。

我们有两种选择:

#define UNUSED(x) (void)(x)

#define UNUSED(x) (x=x)

和一般,定义(x=x)void(x)在功能,即使没有#define

问题是:

其中哪一个是“更好的”?

更好的性能(更快),内存分配(如果有),任何你能想到的技术上的说法。

回答

(void)x是标准的一部分,所以应该更好。使用它时,您不会收到编译器/linters 警告。它也是可移植的,不像特定于实现的解决方案__attribute__((unused)),它不会生成任何代码。x = x可能会产生警告。

关于可以发出的警告的示例x=x

int foo(int bar)
{
    bar = bar;
    return 1;
}

int main()
{
    return foo(2);
}

使用 Clang 10使用-Wall(或仅使用-Wself-assign)编译上述代码会触发以下警告:

$ clang test.c -Wall
test.c:3:9: warning: explicitly assigning value of variable of type 'int' to itself [-Wself-assign]
    bar = bar;
    ~~~ ^ ~~~

短绒同样适用于cppcheck

$ cppcheck test.c --enable=all
Checking test.c ...
test.c:3:9: warning: Redundant assignment of 'bar' to itself. [selfAssignment]
    bar = bar;
        ^
test.c:3:9: style: Variable 'bar' is assigned a value that is never used. [unreadVariable]
    bar = bar;
        ^

当然,这些取决于您使用的工具和您启用的警告,因此它可能会或可能不会生成警告,但将表达式转换为void永远不会生成此类警告。


以上是对于未使用的参数,什么是“更好的”:(x=x)或(void(x))?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>