由int与unsigned int 相加看c++类型转换

来源:互联网 发布:mac与虚拟机共享桌面 编辑:程序博客网 时间:2024/05/16 13:44
 1#include <iostream>
 2using namespace std;
 3
 4int main()
 5{
 6    unsigned int a = 6;
 7    int b = -20;
 8    int d = 6;
 9
10    bool c = (a+b>6);
11    printf("%d\n",c);
12    printf("%d\n",a>b);
13    printf("%u\n",a+b);
14    printf("%u\n",b+d);
15    printf("%d\n",a+b);
16
17    int i,j;
18    unsigned int m,n;
19
20    i = 0x80000000;
21    j = 1;
22
23    m = 0x80000000;
24    n = 1;
25    printf("%d\t%d\n",(i>j),(m>n));
26
27    int p = -1;
28    unsigned int q = -1;
29    printf("%d\n",(p==q));
30
31    printf("%d\t%u\n",q,q);
32
33    return 0;
34}

35

 

程序输出:
zhy@desktop:~/doublemint/factory/interView_Programmer$ ./a.out 
1
0
4294967282
4294967282
-14
0 1
1
-1 4294967295


解释:
unsigned int类型的数据与int类型的数据相运算后,自动转化为unsigned int类型。因此a+b的值不是-14,而是一个unsigned int类型的数4294967382.
1.先说下这个数字怎么来的:
在内存中,负数的存储方式是正数的反码+1.
6:0x00000006
20:0x00000014,补码:0xfffffffeb
-20:0xfffffffec

>>> 0xffffffec+0x06
4294967282L
2.%d,%u输出结果不一样?
int 与unsigned存储形式一样,都是补码形式,区别在于输出的格式控制符,当以%d输出,会认为是有符号数,这样就把最高位的1当成了符号位,也就是负数(0是正数),当以%u输出,会认为是无符号数,这样它会将所有16位的组成都看成是数本身的组成,而没有符号位一说,所以输出结果是由16个1组成的二进制数。

3.关于程序的解释:
int与unsigned int之间,如果只是+/-,是否帶有符號沒有關係。
結果是要看context的,可以賦給int,也可以賦給u_int。
即例如程序里p对应的内存是这样的:0xffffffff
而q对应的也是一样的:0xffffffff
区别在于上下文认为这是一个什么样的格式来读区,是否去读取符号位。
29行输出为真就是因为如此,都提升为unsigned int 类型,当作其来对待,其结果是一样的。不要被绕进去了。

转换的规则:

K & R A.6.5 Arithmetic Conversions
First, if either operand is long double, the other is converted to long double. 
Otherwise, if either operand is double, the other is converted to double. 
Otherwise, if either operand is float, the other is converted to float. 
Otherwise, the integral promotions are performed on both operands; then, if either operand is unsigned long int, the other is converted to unsigned long int. 
Otherwise, if one operand is long int and the other is unsigned int, the effect depends on whether a long int can represent all values of an unsigned int; if so, the unsigned int operand is converted to long int; if not, both are converted to unsigned long int. 
Otherwise, if one operand is long int, the other is converted to long int. 
Otherwise, if either operand is unsigned int, the other is converted to unsigned int. 
Otherwise, both operands have type int.

4.小小的延伸
31行我们可以看到,如何简单输出计算机上int和unsigned int能表示的的最大数?
int的话结果+1再除以2,再减1就是了。

0 0