# 31 C语言中的正负数以及数值溢出

C学习网：链接->C学习网

C训练网：链接->C训练网

1. short a = -10; //负数
2. int b = +10; //正数
3. long c = (-9) + (+12); //负数和正数相加

1. unsigned short a = 12;
2. unsigned int b = 1002;
3. unsigned long c = 9892320;

unsigned n = 100;

unsigned int n = 100;

纯文本复制
1. #include <stdio.h>
2. #include <stdlib.h>
3. int main()
4. {
5. int a1 = 1234, a2 = -1234;
6. unsigned int b1 = 5678, b2 = -5678;
7. printf("a1=%d, a1(u)=%u\n", a1, a1);
8. printf("a2=%d, a2(u)=%u\n", a2, a2);
9. printf("b1=%d, b1(u)=%u\n", b1, b1);
10. printf("b2=%d, b2(u)=%u\n", b2, b2);
11. return 0;
12. }

a1=1234, a1(u)=1234
a2=-1234, a2(u)=4294966062
b1=5678, b1(u)=5678
b2=-5678, b2(u)=4294961618

a2、b2 的输出值之所以很奇怪，与它们在内存中的存储形式有关，我们将在《C语言整数在内存中是如何存储的》一节详细介绍。

## 取值范围和数据溢出

short、int、long 占用的字节数不同，所能表示的数值范围也不同。以32位平台为例，下面是它们的取值范围：

short 2 -32768~32767，即 -215~(215-1)
unsigned short 2 0~65535，即 0~(216-1)
int 4 -2147483648~2147483647，即 -231~(231-1)
unsigned int 4 0~4294967295，即0~(232-1)
long 4 -2147483648~2147483647，即 -231~(231-1)
unsigned long 4 0~4294967295，即0~(232-1)

1. #include <stdio.h>
2. int main()
3. {
4. unsigned int a = 0x100000000;
5. int b = 0xffffffff;
6. printf("a=%u, b=%d\n", a, b);
7. return 0;
8. }

a=0, b=-1