for s="0" and k=20 this code is printing YES infinite number of times but the for loop condition (0<=1-20) is not true. it should print NO. Please help me.
#include <bits/stdc .h>
using namespace std;
int main()
{
string s;
cin>>s;
int k;
cin>>k;
for(int i=0;i<=s.size()-k; i){
cout<<"YES"<<endl;
}
cout<<"NO"<<endl;
return 0;
}
CodePudding user response:
The short answer is: unsigned integer underflow.
To see it more clearly, let's assign the values to variables of type size_t
(which is the type that s.size()
returns):
const size_t ssize = s.size();
const size_t ssize_minus_k = ssize-k;
cout << "ssize=" << ssize << " ssize_minus_k=" << ssize_minus_k << endl;
for(int i=0;i<=ssize_minus_k; i){
cout<<"YES"<<endl;
}
.... with the above lines, the output of the program looks like this:
$ ./a.out
0
20
ssize=1 ssize_minus_k=18446744073709551597
YES
YES
[...]
Now to fix the problem, let's change the type of our variables from size_t
to ssize_t
(note the extra s
, meaning "signed"):
const ssize_t ssize = s.size();
const ssize_t ssize_minus_k = ssize-k;
cout << "ssize=" << ssize << " ssize_minus_k=" << ssize_minus_k << endl;
for(int i=0;i<=ssize_minus_k; i){
cout<<"YES"<<endl;
}
.... and now we get behavior more like what we were expecting:
$ ./a.out
0
20
ssize=1 ssize_minus_k=-19
NO