Home > Net >  Why logical operation is not working properly if i use string::size()
Why logical operation is not working properly if i use string::size()

Time:04-06

string s;
cin >>s ; //input string is: a 
int i=1; 
if(i < s.size()-3 ) cout <<"Yes"<<endl; 
else cout << "No"<<endl;

If the input string is a then output should be No but compiler is showing Yes.

int i = 1;
int len = s.size()-3;
if(i < len ) cout <<"Yes"<<endl;
else cout << "No"<<endl;

If I use the len variable then it is working fine. Now the output is showing No.

CodePudding user response:

s.size() returns an unsigned type.

Since s.size() is 1 in your example, unsigned(1)-3 will wrap to a very large unsigned value. Thus:

if(i < s.size()-3)

will compare i as an unsigned value, and evaluate as true since 1 is less than that large value.

Whereas:

int len = s.size()-3;

will convert the large value into a signed negative value, thus:

if(i < len)

will evaluate as false since 1 is not less than a negative value.

CodePudding user response:

s.size() returns an unsigned int, so if s.size() < 3 then s.size() - 3 becomes very big positive integer. So it can be possible.

  • Related