0

This seems like a very normal piece of code ...but I don't know why its showing abnormal behaviour .

#include <bits/stdc++.h>
using namespace std ;

int main()
{
string s ;
cin>>s;

for(int i =2 ; i < s.length()-2 ; i++)
{
    cout<<"AAAA"<<endl;
}

}

For an input of a string of lenght 1 like 'B' ....The expected output should be nothing ..but instead the output is 'AAAA' infinite times ..can't figure out why the loop runs infiniye times

2 Answers2

2

Not infinite. It will run from 2 (start), to s.length() - 2 (end). Since s is empty, it's size is 0 and it's type is unsigned, substracting 2 from 0 will produce 2^32 - 2 (or 2^64 - 2), which is quite large number.

Radosław Cybulski
  • 2,952
  • 10
  • 21
1

Because s.length() is unsigned, when you subtract 2 it becomes very large (about 2^32 or 2^64) for values of s.length() less than 2. So you need to cast s.length() to int to make this work:

for(int i =2 ; i < int(s.length())-2 ; i++)

And cycle is infinite, because int is signed, so it can't be more than 2^31 or 2^63 (1 bit is reserved for sign).

J. S.
  • 425
  • 4
  • 13