歧义长整数运算? [英] Ambiguity in long integer arithmetic?
问题描述
看一看下面的一段code的:
的#include<&stdio.h中GT;INT主要(无效)
{
int类型的;A = 2147483647;
的printf(A + 1 =%d个\\ t的sizeof(A + 1)=%lu个\\ N,一个+ 1,的sizeof(A + 1));
的printf(A + 1L =%LD \\ t的sizeof(A + 1L)=%lu个\\ N,A + 1L,sizeof的(A + 1L));一个= -1;
的printf(A + 1 =%d个\\ t的sizeof(A + 1)=%lu个\\ N,一个+ 1,的sizeof(A + 1));
的printf(A + 1L =%LD \\ t的sizeof(A + 1)=%lu个\\ N,A + 1L,sizeof的(A + 1L)); //为什么+ 1L不会产生长整型?返回0;
}
这将产生以下的输出:
A + 1 = -2147483648的sizeof(A + 1)= 4
一个+ 1L = 2147483648的sizeof(A + 1L)= 8
一个+ 1 = 0的sizeof(A + 1)= 4
一个+ 1L = 0的sizeof(A + 1)= 8
为什么 A + 1L
在最后一行产量0,而不是一个长整型为4294967296?
为什么+ 1L最后一行中不产生长整数4294967296?
块引用>由于转换
INT
-1到长整型
导致长整型
值为-1,而-1 + 1 = 0
。转换
1
为另一种类型只会导致4294967295
如果目标类型为32位无符号类型(通常,unsigned int类型
是这样的,一般,uint32_t的
,如果有的话)。但随后,加1的值会换到0。因此获得
4294967296
,您将需要一个中间铸,(uint32_t的)一个+ 1L
让
1
首先转换到uint32_t的
值为4294967295
,然后被转换为长
。Have a look at the following piece of code:
#include <stdio.h> int main(void) { int a; a = 2147483647; printf("a + 1 = %d \t sizeof (a + 1) = %lu\n", a + 1, sizeof (a + 1)); printf("a + 1L = %ld \t sizeof (a + 1L) = %lu\n", a + 1L, sizeof (a + 1L)); a = -1; printf("a + 1 = %d \t sizeof (a + 1) = %lu\n", a + 1, sizeof (a + 1)); printf("a + 1L = %ld \t sizeof (a + 1) = %lu\n", a + 1L, sizeof (a + 1L)); //why a + 1L does not yield long integer ? return 0; }
This results in the following output:
a + 1 = -2147483648 sizeof (a + 1) = 4 a + 1L = 2147483648 sizeof (a + 1L) = 8 a + 1 = 0 sizeof (a + 1) = 4 a + 1L = 0 sizeof (a + 1) = 8
Why does
a + 1L
in last line yield 0 instead of a long integer as 4294967296 ?解决方案why a + 1L in last line does not yield long integer as 4294967296 ?
Because converting the
int
-1 to along int
results in thelong int
with value -1, and-1 + 1 = 0
.Converting
-1
to another type would only result in4294967295
if the target type is an unsigned 32-bit type (usually,unsigned int
is such, generally,uint32_t
, if provided). But then, adding 1 to the value would wrap to 0.Thus to obtain
4294967296
, you would need an intermediate cast,(uint32_t)a + 1L
so that
-1
is first converted to theuint32_t
with value4294967295
, and that is then converted tolong
.这篇关于歧义长整数运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!