0

So I don’t know if it’s actually the size() function that’s causing this or not but whenever I run this code I expect it to infinitely loop but it does not. I’m using c++ and visual studio.

string name = “Devin”;
for(int i = 4; i < name.size(); i—-)
{
  printf(“%c”, name[i]);
}
bchesney
  • 11
  • 2
  • 3
    Note that you are comparing signed and unsigned integers. – Adrian Mole Aug 21 '20 at 14:16
  • 2
    This code won't go infinite loop because it will result in compile error due to non-standard quotation marks and lack of semicolon. – MikeCAT Aug 21 '20 at 14:16
  • 2
    `name.size()` returns an unsigned type. When evaluating `i < name.size()`, `i` is promoted to that type. When `i` becomes negative, the conversion does modulo arithmetic, so the result of converting `-1` to to an unsigned type is the maximum value that unsigned type can represent. That value is never less than what `name.size()` can return, so the loop will stop when `i` reaches a value of `-1` (i.e. the 6th iteration). – Peter Aug 21 '20 at 14:20
  • 1
    @Peter Your comment is not suitable as a comment. It should be an answer instead :) – cigien Aug 21 '20 at 14:28
  • @Peter thank you! That makes sense – bchesney Aug 21 '20 at 14:38
  • Also note that you have a semicolon after the "for" declaration, so the printf line will execute only after the for (never if looping infinitely), not as the body of the for. – Malcolm Tucker Aug 21 '20 at 14:59

1 Answers1

0

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 
mo1ein
  • 535
  • 4
  • 18
  • You need to explain why `Because name.size() is unsigned and -1 is a signed number .` causes the loop to stop. That's what the OP is confused about in the first place. – Kevin Aug 21 '20 at 15:31
  • 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``` – mo1ein Aug 21 '20 at 15:45