String.Length () vs. 1 Why do you have incredible results?

Source: Internet
Author: User

Today Debug program found a strange thing, 1 and string.length () is always 1 large, look at the following code

#include <iostream>#include<string>using namespacestd;intMain () {stringstr; STR="123"; intnum=-1; //int len=str.length ();    if(num<str.length ()) {cout<<"-1<str.length ()"; }    Else{cout<<"-1>=str.length ()"; }    return 0;}

The result of the output is: -1>=str.length (), which seems quite bizarre, changed to the following code to see:

#include <iostream>#include<string>using namespacestd;intMain () {stringstr; STR="123"; intnum=-1; intlen=str.length (); if(num<Len) {cout<<"-1<str.length ()"; }    Else{cout<<"-1>=str.length ()"; }    return 0;}

This time the output is -1<str.length ()

These two procedures should seem to output the same results, but actually not, it reminds me of a blog I wrote before, the implicit type of C + + http://www.cnblogs.com/bewolf/p/4358006.html

Look, sure enough, the return value of Str.length () is unsigned int, if you compare directly with-1, the process int will be implicitly converted to unsigned int, so 1 will become a large number, of course "1 is bigger than 3", If you assign Str.length () to a variable of type int, it will be converted like the assigned type, so Str.length () will be converted to the int type, then 1 and a variable of type int, the result is the normal result we want.

String.Length () vs. 1 Why do you have incredible results?

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.