A> = B> = C中的C运算符?

Nil*_*ate 1 c

考虑:

#include<stdio.h>

int main() {
    if (2 >= 1 >= 1)
        printf("1\n");
    if (200 >= 100 >= 100)
        printf("2\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

nyc @ nyc:〜/ PRG $ gcc sample.c

nyc @ nyc:〜/ PRG $ ./a.out 1

为什么即使第二个表达式的计算结果为TRUE,该程序也只打印1?

Spi*_*rix 10

C不支持这样的链接运算符.您必须将该表达式划分为两个,由逻辑AND运算符分隔:

if(2 >= 1 && 1 >= 1)
if(200 >= 100 && 100 >= 100)
Run Code Online (Sandbox Code Playgroud)

否则,执行为

if((2 >= 1) >= 1)
if((200 >= 100) >= 100)
Run Code Online (Sandbox Code Playgroud)

并且左边的部分将首先执行,如果该条件为真,将评估为1,并且将评估为0,如果为false,则上述条件变为

if(1 >= 1) /* which is true */
if(1 >= 100) /* which is false */
Run Code Online (Sandbox Code Playgroud)


Bat*_*eba 5

第二个表达式也不会计算为true。

C标准定义了比较运算符(“>”,“> =”,“ ==”等)以返回int结果(0(代表false)或1(代表true))。此外>=,从左到右进行评估。(通常将其称为运算符的关联性)。

所以2>=1>=1等于(2>=1)>=1。这是1 >= 1,其值为1。

200>=100>=100被计算为(200>=100)>=100这是1 >= 100其评估为0。