C ++ Primer Plus Reading Notes,
This article aims to record some key knowledge points in the fifth edition of C ++ Primer Plus for future reference. This article will be updated constantly ......
Chapter I. III
1. unsigned integers cannot store negative values. The advantage is that they can increase the maximum value that a variable can store. For example, if the short value range is-32768-32767, the value range of the unsigned version is 0-65535. Assume that there is a short variable sam and an unsigned short variable sue, set the short value to the maximum value, for example, 32767, and Add 1 to both variables. This is no problem for sue, but the sam value is changed from 32767 to-32768! Similarly, for sam, setting its value to 0 and then subtracting 1 will not be a problem; but for sue, setting its value to 0 will go to 1 and it will become 65535!
Note:
string str = "123456";if (-1 < str.size()) cout << "win\n";else cout << "lose\n";
Your answer is win, right? Sorry, NO, the answer is: lose !!!
Why? In fact, this is a very simple problem, with different types.
-1: The default value isint
,size()
The return type issize_t
That isunsigned int
.
1 size_t x = 1; 2 int y =-1; 3 cout <x + y <endl; // 0 (-1 is the maximum integer that nusigned int can represent, after 1 is added, it becomes 0) 4 cout <typeid (x + y ). name () <endl; // unsigned int
For two types of operations, int-1 will be automatically convertedunsigned int
, That is:
1 (unsigned int) + -1 (int) 0000...0001(unsigned int) + 1111...1111(int)= 0000...0001(unsigned int) + 1111...1111(unsigned int)= 0000...0000(unsigned int)
Obviously, after-1 of the int type is converted to unsigned int, it will become a very large positive number.