[英]Trouble Understanding Logical expression in C programming
I am learning C on my own and following a book with exercises that do not have answers. 我自己学习C,并且正在学习一本没有答案的练习。 I am having trouble understanding why the below expression evaluates to "true" or "1" when running it in my compiler.
我无法理解为什么在编译器中运行以下表达式时其结果为“ true”或“ 1”。 I understand precedence, associativity, and how logical operators work, but the
a +=
trips me up. 我了解优先级,关联性以及逻辑运算符的工作方式,但是
a +=
我感到震惊。 I don't know how that relates to true and false. 我不知道这与是非有关。 I appreciate any help or explanation as to how this evaluates to true.
感谢您提供任何帮助或解释,以帮助您评估结果是否正确。
int a = 1, b = 2, c = 3;
a += !b && c == ! 5;
a += !b && c == ! 5
parses as 解析为
a += ((!b) && (c == (! 5)))
We can evaluate each sub-expression in turn: 我们可以依次评估每个子表达式:
b
is 2
. b
是2
。 !b
is 0
(because !
turns all non-zero values into zero, and zero into one). !b
为0
(因为!
将所有非零值都变成零,而零则变成一)。 0 && ...
does not evaluate its right-hand side but returns 0
immediately. 0 && ...
不评估其右侧,但立即返回0
。 a += 0
is equivalent to a = a + 0
, which doesn't change the value of a
, but returns its new value (same as the old value in this case), 1
. a += 0
等效于a = a + 0
,这不改变的值a
,但(在这种情况下相同的旧值)返回它的新值, 1
。 1
is not zero, so it's true. 1
不是零,所以它是正确的。 In case this is what's tripping you up: The assignment operators are, well, operators. 万一这是让您烦恼的事情:赋值运算符就是运算符。 The have an effect (assigning a value to a variable), but they also have a result.
具有效果(将值分配给变量),但它们也具有结果。 For all assignment operators the result is the value being assigned:
对于所有赋值运算符,结果是要赋值的值:
int n = 2;
printf("%d\n", n += 3);
outputs 5
and also sets n
to 5
. 输出
5
并将n
设置为5
。
Just for completeness, c == (!5)
would have evaluated as follows: 仅出于完整性考虑,
c == (!5)
评估如下:
!5
is 0
. !5
为0
。 c == 0
is 0
(because c
is 3
and ==
returns 1
for true and 0
for false). c == 0
为0
(因为c
为3
并且==
返回1
表示true, 0
表示false)。 Expression a += !b && c == ! 5;
表达式
a += !b && c == ! 5;
a += !b && c == ! 5;
is equivalent to a = a + (!b && c == ! 5);
等价于
a = a + (!b && c == ! 5);
. 。 Hope that helps, and I hope that you never face such an expression in practice.
希望能有所帮助,并且我希望您在实践中永远不会面对这样的表达。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.