问题描述
你好,
我在一些代码中偶然发现了这个:
n = !! x;
我已经运行它了''n''总是0或1.是''!!''是一个操作员(它是什么?
叫做?)是标准/便携式吗?
-
benkibbey ::: bjk AT arbornet DOT org
n = !! x;
应相当于:
n =!(!x) ;
甚至:
n =!(!(x));
如果x非零,则n应为1 ,如果x为零,则为0。
有了这个主意吗?
Alex
是的。
int i = 42;
int j =!i; / *用0 * /
int k初始化''j''; = !!我; / *用1 * /
int m =!j初始化''k''; / *初始化''m''用1 * /
逻辑
非运算符的'双重应用''的典型原因是将非零值(在逻辑上将
总是计算为''true'')转换为特定的''true''值(在
中,这种情况为一(1))。需要这样做的原因取决于应用程序上的
。这是一个简单的人为例子:
#include< stdio.h>
/ *零值无效,任何非零值有效* /
void validate(int value)
{
static const char * msg [] = {" invalid"," valid"};
printf(" value%d is%s \ n",msg [ !! i]);
/ *注意!! 0总是正好0 * /
}
int main ()
{
验证(42);
返回0;
}
IOW,!42 == 0,!! 42 == 1,!! 42!= 42
如果有的话需要其他特定的真实价值,人们只需要对价值1执行更多算术(例如,添加
一些价值)。
-Mike
hello,
I''ve stumbled upon this in some code:
n = !!x;
I''ve ran it and ''n'' is always either 0 or 1. Is ''!!'' an operator (what''s it
called?) and is it standard/portable?
--
b e n k i b b e y ::: bjk AT arbornet DOT org
n = !!x;
should be equivalent to:
n = !(!x);
or even:
n = !(!(x));
And n should be 1 if x is nonzero, 0 if x is zero.
Got the idea?
Alex
Yes.
int i = 42;
int j = !i; /* initializes ''j'' with 0 */
int k; = !!i; /* initializes ''k'' with 1 */
int m = !j; /* initializes ''m'' with 1 */
The typical reason for this ''double application'' of the logical
not operator is to transform a nonzero value (which logically
always evaluates to ''true'') into a specific ''true'' value (in
this case one (1). The reason for needing to do this depends
upon the application. Here''s a simple contrived example:
#include <stdio.h>
/* zero value is invalid, any nonzero value is valid */
void validate(int value)
{
static const char *msg[] = {"invalid", "valid"};
printf("value %d is %s\n", msg[!!i]);
/* note that !!0 always is exactly 0 */
}
int main()
{
validate(42);
return 0;
}
IOW, !42 == 0 , !!42 == 1 , !!42 != 42
If some other specific ''true'' value were needed, one would
simply perform more arithmetic upon the value one (e.g. add
some value).
-Mike
It means ''not not x'', evaluating to 0 if x is 0 or to 1 if x is not 0.
--
Devaraja (Xdevaraja87^gmail^c0mX)
Linux Registerd User #338167
http://counter.li.org
这篇关于!!, 它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!