C++ unsigned types

Unsigned type unsigned and signed type signed

Signed types can represent 0, positive numbers, and negative numbers, while unsigned types can only represent numbers greater than or equal to 0.

type conversion

The range of values ​​that the type can represent determines the conversion process

  • When we assign a value to an unsigned type that is outside the range it represents, the result is the remainder of the initial value modulo the total number of values ​​represented by the unsigned type.
	unsigned u = 10;
	int i = -42;
	//u+i,相加前首先把整数-43转换成无符号数(把负数转换成无符号数类似于直接给无符号数赋一个负值)
	//因为int是32位,因此它能表示数值总数位2^32,所以-42转换为无符号数=(-42+2^32)=4294967254
	// 4294967254+19=4294967264 即输出结果
	cout<<u+i<<endl;
	unsigned u1 = 42, u2 = 10;
	cout<<u1-u2<<endl;
	cout<<u2-u1<<endl;

Error case

// 由于无符号数永远不会小于0,因此这是个死循环
for(unsigned i = 10;i>=0;i--)
cout<<i<<endl;

Guess you like

Origin blog.csdn.net/weixin_47020721/article/details/132801940