如何c在这两种情况下工作和什么差异

ase*_*eed 0 c c++ visual-c++

为什么结果是x = 1 y = 3 res = 1

    int x = 7, y = 3;
    int res;
    res = (x = y < 2 ||  x != 1);
    printf("x = %d    y = %d    res = %d\n", x, y, res);
Run Code Online (Sandbox Code Playgroud)

并且使用此代码,结果是y <2,因此False为0,因此左值x = 0,因此res = 0

    res= (x = y < 2);  //||  x != 1);
    printf("x = %d    y = %d    res= %d\n", x, y, res);
Run Code Online (Sandbox Code Playgroud)

Ton*_*roy 5

res = (x = y < 2 ||  x != 1);
Run Code Online (Sandbox Code Playgroud)

......评估为......

res = (x = ((y < 2) || (x != 1)));
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到C++的运算符优先级- 对于您使用的运算符,C类似.

所以x = 7, y = 3......

res = (x = ((3 < 2) || (7 != 1)));

res = (x = (false || true));  // || is "logical-OR", tests if either true

res = (x = true);

res = (x = 1);   // standard conversion from bool to int

res = 1;
Run Code Online (Sandbox Code Playgroud)

对于您的第二个更简单的陈述:

 res = (x = y < 2);
 res = (x = (y < 2));
 res = (x = (3 < 2));
 res = (x = false);
 res = (x = 0);  // standard conversion from bool false to int 0
 res = 0;
Run Code Online (Sandbox Code Playgroud)

在C中,即使你#include <stdbool.h><,!=并且||运算符将1立即为"真实"测试和0"假" 测试产生,并且没有像C++那样单独的"标准转换".Allan的回答很好地描述了C评估步骤.