C ++ Primer Plus Reading Notes,

Source: Internet
Author: User

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_tThat 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.