当在C使用双逻辑非(!)? [英] When to use the double logical not (!!) in C?
问题描述
什么是用C否定两次一些有效的用途?例如,是这样的:
What are some valid uses for negating twice in C? For example, something like:
if (!!my_cond) {
}
据我了解,在 !!
将保证 !! my_cond
将是0,如果 my_cond
是假
否则为1。当你不断的需求的使用呢?
As I understand, the !!
will guarantee that the !!my_cond
will be 0 if my_cond
is false
and 1 otherwise. When would you ever need to use this?
推荐答案
在你正在显示它的背景下,这是没用的,因为本身的价值将评估为 0
或 1
。
In the context that you are showing it, it is useless, since the value itself would evaluate to 0
or 1
.
它可以在不会做这样的布尔的转换,如算术或索引
It can be usefull in a context that would not do such a "Boolean" conversion, such as arithmetic or indexing
size_t zerovalues[2] = { 0, 0, };
for (size_t i = 0; i < N; ++i)
++zerovalues[!!A[i]];
在最后你不得不 A
的值0的数量 zerovalues [0]
和那些没有在 zerovalues数[1]
At the end you'd have the number of values 0 of A
in zerovalues[0]
and the number of those that aren't in zerovalues[1]
这篇关于当在C使用双逻辑非(!)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!