C For Loop Not Working?
Question
I'm working with strings in C as character arrays, and I'm trying to ensure that I can dynamically pass values into my for loops.
The following code works, no problem:
for (int i = -6; i < 11; i++) {
int test = OverlapStrength(fragments[1], fragments[2], i, 0);
printf("%d\n", test);
}
In fact, this code works, too:
for (int i = -strlen(fragments[2]) + 1; i < 11; i++) {
int test = OverlapStrength(fragments[1], fragments[2], i, 0);
printf("%d\n", test);
}
But for some reason, this code doesn't print ANYTHING:
for (int i = -strlen(fragments[2]) + 1; i < strlen(fragments[1]); i++) {
int test = OverlapStrength(fragments[1], fragments[2], i, 0);
printf("%d\n", test);
}
I have checked the values for both -strlen(fragments[2]) + 1
and strlen(fragments[1])
just before the loop and they check out to -6 and 11 respectively. Clearly the loop works when I place those values directly into their places, but when I replace the second one with the strlen
calculations, it breaks and I can't figure out why for the life of me. Help?
Edit
OverlapStrength takes its arguments as constants so I can't change them, so I'm pretty sure I'm not changing the fragments as I go. Here's the method declaration:
int OverlapStrength(const char one[], const char two[], int startOne, int startTwo)
The contents of the fragments shouldn't be important, but they're simply strings that I'm trying to piece back together from overlapping fragments. I have already checked that my fragments are all coming out properly and that their lengths are computed properly when done outside of declaring this loop.
Solution
strlen
returns value of type size_t
, which is probably a typedef for unsigned int
for your case. Then you are comparing a signed int
(i
) and unsigned int
(strlen(...)
). C decides then to cast your signed value to an unsigned type (because of default type promotions). -6
converted to unsigned int is 4294967290
, therefore your comparison is false, so the loop ends.
To fix this, you can for example cast strlen
to a signed value, e.g.:
i < (int) strlen(fragments[1])
OTHER TIPS
In a for-loop, the codition (the i < strlen(fragments[1])
part) gets evaluated on every iteration. If OverlapStrength
changes the value of fragments[1]
to something less than i
, the loop will abort.
To fix this, use a constant:
int loopUntil = strlen(fragments[1]);
for (int i = -strlen(fragments[2]) + 1; i < loopUntil; i++) {
int test = OverlapStrength(fragments[1], fragments[2], i, 0);
printf("%d\n", test);
}