且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

歧义长整数运算?

更新时间:2023-09-29 09:06:52


  

为什么+ 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 a long int results in the long int with value -1, and -1 + 1 = 0.

Converting -1 to another type would only result in 4294967295 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 the uint32_t with value 4294967295, and that is then converted to long.