首先明确一点,当表达式中存在有符号类型和无符号类型时。
两个无符号数相加有进位的概念。
两个有符号数相加有溢出的概念。
<br>
1 #include<stdio.h>
2 char getChar(int x, int y)
3 {
4 char c ;
5 unsigned int a=x ;
6 (a+y>10) ? (c=1) : (c=2) ;
7 return c ;
8 }
9 int main (void)
10 {
11 char c1=getChar( 7 , 4 );
12 char c2=getChar( 7 , 3 );
13 char c3=getChar( 7, -7);
14 char c4=getChar( 7, -8 );
15
16 printf( " c1 = %d " , c1 );
17 printf( " c2 = %d " , c2 );
18 printf( " c3 = %d " , c3 );
19 printf( " c4 = %d " , c4 );
20
21 return 0 ;
22 }
</br>
程序中第五行a是无符号数,所在在第六行中的y会转换为无符号类型的数,在于a相加,然后再与10进行比较。
分析如下:
代码13行中,传入的两个数分别是7和-7,表达式中存在有符号类型与无符号类型,所有将所有操作数都要转换为无符号类型。因此-7要转换成无符号类型,而-7所对应的二进制为
-7:1 1 1 1 1 0 0 1 (补码), 7:0 0 0 0 0 1 1 1
1 1 1 1 1 0 0 1
+ 0 0 0 0 0 1 1 1
——————————————
1 0 0 0 0 0 0 0 0
两个无符号整数的计算结果产生了进位(第9位),除进位位外,其余8位均为0,因此,计算结果是0. 因为0比10小,因此函数返回 2。
代码14行,传入的参数7和-8,表达式中存在有符号类型与无符号类型,所有将所有操作数都要转换为无符号类型。因此-8要转换成无符号类型,而-8所对应的二进制为
-8 :1 1 1 1 1 0 0 0(补码), 7:0 0 0 0 0 1 1 1
1 1 1 1 1 0 0 0
+ 0 0 0 0 0 1 1 1
———————————————
1 1 1 1 1 1 1 1
没有产生进位,1 1 1 1 1 1 1 1 所对应的十进制为255,且大于0,因此函数返回 1
两个无符号数相加有进位的概念。
两个有符号数相加有溢出的概念。
<br>
1 #include<stdio.h>
2 char getChar(int x, int y)
3 {
4 char c ;
5 unsigned int a=x ;
6 (a+y>10) ? (c=1) : (c=2) ;
7 return c ;
8 }
9 int main (void)
10 {
11 char c1=getChar( 7 , 4 );
12 char c2=getChar( 7 , 3 );
13 char c3=getChar( 7, -7);
14 char c4=getChar( 7, -8 );
15
16 printf( " c1 = %d " , c1 );
17 printf( " c2 = %d " , c2 );
18 printf( " c3 = %d " , c3 );
19 printf( " c4 = %d " , c4 );
20
21 return 0 ;
22 }
</br>
程序中第五行a是无符号数,所在在第六行中的y会转换为无符号类型的数,在于a相加,然后再与10进行比较。
分析如下:
代码13行中,传入的两个数分别是7和-7,表达式中存在有符号类型与无符号类型,所有将所有操作数都要转换为无符号类型。因此-7要转换成无符号类型,而-7所对应的二进制为
-7:1 1 1 1 1 0 0 1 (补码), 7:0 0 0 0 0 1 1 1
1 1 1 1 1 0 0 1
+ 0 0 0 0 0 1 1 1
——————————————
1 0 0 0 0 0 0 0 0
两个无符号整数的计算结果产生了进位(第9位),除进位位外,其余8位均为0,因此,计算结果是0. 因为0比10小,因此函数返回 2。
代码14行,传入的参数7和-8,表达式中存在有符号类型与无符号类型,所有将所有操作数都要转换为无符号类型。因此-8要转换成无符号类型,而-8所对应的二进制为
-8 :1 1 1 1 1 0 0 0(补码), 7:0 0 0 0 0 1 1 1
1 1 1 1 1 0 0 0
+ 0 0 0 0 0 1 1 1
———————————————
1 1 1 1 1 1 1 1
没有产生进位,1 1 1 1 1 1 1 1 所对应的十进制为255,且大于0,因此函数返回 1