如何||和&&作品 [英] How || and && works
问题描述
main( ) {
int i = 4, j = -1, k = 0, w, x, y, z ;
w = i || j || k ;
x = i && j && k ;
y = i || j && k ;
z = i && j || k ;
printf ( "\nw = %d x = %d y = %d z = %d", w, x, y, z ) ;
}
我只是在学习C,并且遇到了这段代码.老实说,我不知道w,x,y和z被分配了什么.显然,输出如下:
I'm just learning C and I came across this code. I honestly dont know what w, x, y and z are assigned to. Apparently the output is as follows:
w = 1 x = 0 y = 1 z = 1
"w"如何等于1?我不明白.
How is 'w' equal to 1? I dont get it.
推荐答案
||
是逻辑或运算符.从C11 s6.5.14逻辑或运算符
||
is the logical OR operator. From C11 s6.5.14 Logical OR operator
||如果运算符之一比较,则运算符应产生1不等于0;否则,结果为0.结果的类型为int.
The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
... ||操作员保证从左到右的评估;
...the || operator guarantees left-to-right evaluation;
将其应用于 w
的计算中
w = i || j || k == (i || j) || k
== (non-zero || non-zero) || 0
== 1 || 0
== 1
x
, y
, z
的计算相似.C11 s6.5.13.3 声明&&
运算符的结果应为0或1.
Calculations for x
, y
, z
are similar. C11 s6.5.13.3 states that the result from the &&
operator shall be 0 or 1.
这篇关于如何||和&&作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!