什么是 "better" : (x=x) or (void(x)) for unused parameters?
What is "better" : (x=x) or (void(x)) for unused parameters?
我们都知道,有时我们会获取函数的参数,但我们并没有真正使用它们。
我们不想收到任何编译器警告,因此我们需要以某种方式“使用”但不是真正使用这些参数。
我们有 2 个选项:
#define UNUSED(x) (void)(x)
#define UNUSED(x) (x=x)
一般来说,
在函数中定义 (x=x)
或 void(x)
,即使没有 #define
.
问题是:
其中哪一个“更好”?
更好的性能(更快),内存分配(如果有的话),任何你能想到的技术。
(void)x
是标准的一部分,所以应该更好。使用它时不会收到 compilers/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;
~~~ ^ ~~~
linters 也一样 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
永远不会生成此类警告。
Which one of these is "better"?
#define UNUSED(x) (void)(x)
因为这对于您所做的事情来说几乎是标准的。
Better for performance (quicker), memory allocation(if any), anything you can think about speaking technically.
如果你激活了优化,如果你关心性能,你应该激活,这些东西无论如何都会被优化掉。
我们都知道,有时我们会获取函数的参数,但我们并没有真正使用它们。
我们不想收到任何编译器警告,因此我们需要以某种方式“使用”但不是真正使用这些参数。
我们有 2 个选项:
#define UNUSED(x) (void)(x)
#define UNUSED(x) (x=x)
一般来说,
在函数中定义 (x=x)
或 void(x)
,即使没有 #define
.
问题是:
其中哪一个“更好”?
更好的性能(更快),内存分配(如果有的话),任何你能想到的技术。
(void)x
是标准的一部分,所以应该更好。使用它时不会收到 compilers/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;
~~~ ^ ~~~
linters 也一样 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
永远不会生成此类警告。
Which one of these is "better"?
#define UNUSED(x) (void)(x)
因为这对于您所做的事情来说几乎是标准的。
Better for performance (quicker), memory allocation(if any), anything you can think about speaking technically.
如果你激活了优化,如果你关心性能,你应该激活,这些东西无论如何都会被优化掉。