php ifp,Logical operators(逻辑运算符)

逻辑运算符对其操作数应用标准布尔代数运算。

OperatorOperator nameExampleResult!logical NOT!athe logical negation of a

&&logical ANDa && bthe logical AND of a and b

||logical ORa || bthe logical OR of a and b

逻辑 NOT

逻辑 NOT 表达式具有这种形式。

! expression

其中

expression-an expression of any scalar type

逻辑 NOT 运算符具有类型int。它的值是0如果表达式评估为一个比较不等于零的值。它的值是1如果表达式计算出的值等于零。(如此!E相同(0==E))。

#include #include #include int main(void){

bool b = !(2+2 == 4); // not true    printf("!(2+2==4) = %s\n", b ? "true" : "false");

int n = isspace('a'); // zero if 'a' is a space, nonzero otherwise

int x = !!n; // "bang-bang", common C idiom for mapping integers to [0,1]                 // (all non-zero values become 1)

char *a[2] = {"nonspace", "space"};    printf("%s\n", a[x]); // now x can be safely used as an index to array of 2 ints}

输出:

!(2+2==4) = falsenonspace

逻辑 AND

逻辑“与”表达式具有这种形式。

lhs && rhs

其中

lhs-an expression of any scalar typerhs-an expression of any scalar type, which is only evaluated if lhs does not compare equal to 0

逻辑 AND 运算符具有类型int和值,1如果 lhs 和rhs 比较不等于零。它具有其他值0(如果lhs或rhs或两者都等于零)。

lhs评估后有一个序列点。如果lhs的结果等于零,则根本不评估rhs(所谓的短路评估)。

#include #include int main(void){

bool b = 2+2==4 && 2*2==4; // b == true

1 > 2 && puts("this won't print");

char *p = "abc";    if(p && *p) // common C idiom: if p is not null                // AND if p does not point at the end of the string    {           // (note that thanks to short-circuit evaluation, this                //  will not attempt to dereference a null pointer)    // ...      // ... then do some string processing    }}

逻辑或

逻辑 OR 表达式具有表格。

lhs || rhs

其中

lhs-an expression of any scalar typerhs-an expression of any scalar type, which is only evaluated if lhs compares equal to 0

如果lhs或rhs比较不等于零,则逻辑或运算符具有类型int和值1。它有价值0否则(如果lhs和rhs比较等于零)。

lhs 评估后有一个序列点。如果lhs的结果不等于零,则根本不评估 rhs(所谓的短路评估)。

#include #include #include #include int main(void){

bool b = 2+2 == 4 || 2+2 == 5; // true    printf("true or false = %s\n", b ? "true" : "false");

// logical OR can be used simialar to perl's "or die", as long as rhs has scalar type    fopen("test.txt", "r") || printf("could not open test.txt: %s\n", strerror(errno));}

可能的输出:

true or false = truecould not open test.txt: No such file or directory

参考

C11 standard (ISO/IEC 9899:2011):6.5.3.3 Unary arithmetic operators (p: 89)

6.5.13 Logical AND operator (p: 99)

6.5.14 Logical OR operator (p: 99)

C99 standard (ISO/IEC 9899:1999):6.5.3.3 Unary arithmetic operators (p: 79)

6.5.13 Logical AND operator (p: 89)

6.5.14 Logical OR operator (p: 89)

C89/C90 standard (ISO/IEC 9899:1990):3.3.3.3 Unary arithmetic operators

3.3.13 Logical AND operator

3.3.14 Logical OR operator

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值