What's the difference?

    string s= "codechef";
    int mxlen= -1;
    if(s.length()>mxlen) cout<<1<<endl;
    else cout<<0<<endl;

The above code outputs => 0
Whereas the below code outputs => 1

    string s= "codechef";
    int mxlen= -1;
    int tempLen= s.length();
    if(tempLen>mxlen) cout<<1<<endl;
    else cout<<0<<endl;

What’s the difference in the two given codes?

2 Likes

string s= “codechef”;
int mxlen= -1;
if((int)s.length()>mxlen) cout<<1<<endl;
else cout<<0<<endl;

now output comes 1. here s.length gives value in unsined int. so mxlen is also convereted so when -1 converted into unsigned it return 4294967295(the range of unsined int)-1 .thats why this comes

2 Likes