!! c运算符,是两个NOT吗?

我读这段代码,并有这行


 switch (!!up + !!left) {

什么是!!运算符?两个逻辑非?


BIG阳
浏览 481回答 3
3回答

MMTTMM

是的,不是两个。!!a是1if a非零,0if a是0您可以将其!!视为钳制{0,1}。我个人觉得这种用法看起来很不好。

幕布斯6054654

您可以这样想象:!(!(a))如果您一步一步做,这很有意义result = !42;    //Result = 0result = !(!42)  //Result = 1 because !0 = 1  这将返回1任何数字(-42、4.2f等),但只有0时会返回result = !0;    //Result = 1result = !(!0)  //result = 0

元芳怎么了

你是对的。这是两个不。要了解为什么要这样做,请尝试以下代码:#include <stdio.h>int foo(const int a){&nbsp; &nbsp; return !!a;}int main(){&nbsp; &nbsp; const int b = foo(7);&nbsp; &nbsp; printf(&nbsp; &nbsp; &nbsp; &nbsp; "The boolean value is %d, "&nbsp; &nbsp; &nbsp; &nbsp; "where 1 means true and 0 means false.\n",&nbsp; &nbsp; &nbsp; &nbsp; b&nbsp; &nbsp; );&nbsp; &nbsp; return 0;}它输出The boolean value is 1, where 1 means true and 0 means false. 如果删除!!,则输出The boolean value is 7, where 1 means true and 0 means false.
打开App,查看更多内容
随时随地看视频慕课网APP