[英]Decrementing size_t on the right hand of assignment
Why is idx1
-1 in this case?为什么在这种情况下
idx1
-1 ?
long long idx = (size_t)0 - 1;
cout << (size_t)0 - 1;
This prints ULLONG_MAX
这将打印
ULLONG_MAX
cout << idx;
This prints -1这打印 -1
What would change if idx
was integer instead?如果
idx
改为 integer 会发生什么变化?
In this statement在这份声明中
cout << (size_t)0 - 1;
the type of the expression (size_t)0 - 1
is the unsigned integer type size_t
due to the usual arithmetic conversions.由于通常的算术转换,表达式
(size_t)0 - 1
的类型是无符号 integer 类型size_t
。 Because it can't be negative, it has the value ULLONG_MAX
(it seems that in the used system the type size_t is defined as an alias for the type unsigned long long int
).因为它不能是负数,所以它的值
ULLONG_MAX
(似乎在使用的系统中,类型 size_t 被定义为类型unsigned long long int
的别名)。
In this declaration在这份声明中
long long idx = (size_t)0 - 1;
the initializer is converted to the signed type long long int that is to the type of the declared object.初始值设定项转换为有符号类型 long long int,即声明的 object 的类型。 The UNIT_MAX value cannot fit into a signed long long, so it gives -1.
UNIT_MAX 值不能放入有符号的 long long 中,因此它给出 -1。
As the width of the type size_t
in the used system is the same as the width of the type long long int.由于所用系统中
size_t
类型的宽度与 long long int 类型的宽度相同。 So the internal representation of the initializer of the type size_t is interpreted as a value of the type long long That is the most significant bit of the unsigned initializer is considered as the sign bit.int.所以 size_t 类型的初始化器的内部表示被解释为 long long 类型的值,即无符号初始化器的最高有效位被认为是符号 bit.int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.