Why is the return value of string. find ()-1, string. find-1?

Source: Internet
Author: User

Why is the return value of string. find ()-1, string. find-1?


It seems that I have seen this problem for a long time before. I cannot remember it. I encountered this problem again when I wrote a string today. The definition in the book is "string. when find () is not found, a large value is returned. Some people on the Internet say it is-1, both of which are true, because integers are stored in the computer in the form of supplementary codes, if the second digit of a high value is 1 when one integer is less than one, then the second digit is negative, if the second digit of A High integer includes all 1 after the second digit, then-1 is used in the case of one less digit. String. the large number returned by find () is the power 32 of 2, while the int and long integer expressed in 4 bytes can only represent the power 31 of 2 at most, the value of the last 32 bits stored by the power of 2 is exactly the same as the complement code of-1: 11111111 11111111 11111111 11111111; if the value is assigned to an int or long type, it is naturally-1.

The following is the C ++ verification code.

#include <iostream>#include <string>using namespace std;int main(){    string str = "helloworld!";    int i;    long l;    i = str.find("y");    l = str.find("y");    cout<<i<<" "<<l<<" "<<str.find("y")<<endl;    return 0;}


The result is-1-1 4294967295

4294967295 minus one for 32 places equal to 2



Find () in string

There is no way. Unless you write a method yourself, input the array parameter, and return the array value.

Why is the return value 1?

The sizeof function only returns the number of bytes in memory occupied by this type. Plus the asterisk (*), it is a pointer variable and the pointer occupies 1 byte. Therefore, 1 is returned. If the asterisk (*) is removed from the array, which occupies four bytes, 4 is returned.

Related Article

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.