[英]what is actual value of variable t of type size_t when it is assigned negative value?(can be unsigned int instead of size_t)
将-1分配给size_t
类型的变量t
并检查它是否与-1和4294967295相等( FFFFFFFF ,2的补码 -1 ;我的系统为64位 ;值可能随系统而异),然后在两种情况下均返回1即如此 。
代码是
int main(){
unsigned int t = 10;
cout<<"t = -1: "<<(t==-1); //checks if t is -1
cout<<"\nt = 4294967295: "<<(t==4294967295); //checks if t is 4294967295
cout<<"\nt: "<<t; //printing actual value of t
int p = t; //typecasting it to int
cout<<"\np: "<<p; //printing value of p
}
实际输出为
t = -1: 1
t = 4294967295: 1
t: 4294967295
p: -1
两次检查(t==-1)
和(t==4294697295)
都返回1
,但输出t = 4294697295
和输出p = -1
。 是变量t保持两个值,即-1和4294697295 。 绝对不是这样。
需要帮助。 系统内部实际发生了什么?
将带符号的值与无符号的值进行比较时,在比较之前将带符号的值转换为无符号的值。 这是在编译过程中完成的。 因此t==-1
变成t==4294967295u
和t==4294967295
(有符号整数文字)变成t==4294967295u
。
参考: http : //eel.is/c++draft/expr.arith.conv
(1.5.3)否则,如果具有无符号整数类型的操作数的秩大于或等于另一个操作数的类型的秩,则应将具有符号整数类型的操作数转换为具有无符号整数的操作数的类型类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.