和-1的操作
在代码中实施逻辑操作时,我发现了一种现象,不应在IF语句中输入它。 事实证明,这是-1和自然数的和(&&)
操作。
我不知道为什么值1在下面的相同代码中打印。 我进行了直接计算,例如1的补充和2的补充,但没有1出来。
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = -1;
int c = a && b;
printf("test = %d",c);
return 0;
}
While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&)
operation of -1 and natural numbers.
I don't know why the value 1 is printed in the same code below.
I ran direct calculations such as 1's complement and 2's complement, but no 1 came out.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = -1;
int c = a && b;
printf("test = %d",c);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
expression
a&amp;&amp; b
是bool
类型,是true
或false
:它是true
If an如果a
和b
是非零的,false
否则。正如您的问题所提到的补充方案(请注意,从C ++ 20中,int
始终是2的补充),-0和+0都是为零的,目的是&amp;&amp; < /代码>。
当分配给
int
类型c
时,bool
类型被隐式转换为0(如果false
)或1(如果true
)。(在C中,分析相似,除了
a&amp;&amp; b
是int
类型,因此不进行隐式转换。)The expression
a && b
is abool
type and is eithertrue
orfalse
: it istrue
if and only if botha
andb
are non-zero, andfalse
otherwise. As your question mentions complementing schemes (note that from C++20, anint
is always 2's complement), -0 and +0 are both zero for the purpose of&&
.When assigned to the
int
typec
, thatbool
type is converted implicitly to either 0 (iffalse
) or 1 (iftrue
).(In C the analysis is similar except that
a && b
is anint
type, and the implicit conversion therefore does not take place.)