Consider your code like this:
string name = "Devin";
for(int i = 4; i < name.size(); i--)
cout << name[i] << " i :" << i << "\n";
your output is:
n i: 4
i i: 3
v i: 2
e i: 1
D i: 0
Because
When comparing signed
with unsigned
, the compiler converts the signed
value to unsigned
. For equality, this doesn't matter, -1 == (unsigned) -1
. For other comparisons it matters, e.g. the following is true: -1 > 2U
.
name.size()
is unsigned
and i
is going to unsigned
number now and loop is end. For better understanding ; I used 5
instead of name.size()
because "Devin"
length is 5
.
for(int i = 4; i < 5; i--)
cout<< name[i]<<" i: "<<i<<"\n";
And output is :
// Your i is going to negetive and infinity loop like
i : -1
i : -2
.
.
.
// and maybe you got segmentation fault (core dumped)
// Because your string just have 5 indexes