Char Array - Why is the loop not infinite?

I wrote the following code to flip a line in C. The code seems to work correctly, and so I got confused. Does anyone know why there is no mistake here? I was expecting an array outside the bounds or an infinite loop in a for loop, but it seems like the loop is interrupted before it gets negative values.

#include <stdio.h> #include <string.h> void reverse(char* str); void reverse(char* str) { size_t len = strlen(str); for(int i = (int)len-1; i<=len; i--) { printf("%c", str[i]); } } int main (int argc, const char * argv[]) { char string[] = {'h', 'e', 'l', 'l', 'o', '\0'}; reverse(string); return 0; } 
+6
source share
1 answer

size_t is usually defined as unsigned. When you compare a signed and unsigned number or an equal rank, the signed number is converted to unsigned. Since the signed number is probably presented in two additions in your machine, the negative numbers are actually larger.

So, once i reaches -1, this is more than the comparison thinks that it is more than len.

You can see this happening by turning on the warning in your compiler.

Compiling your program with clang -Weverything produces this warning

 unsigned.c:10:30: warning: comparison of integers of different signs: 'int' and 'size_t' (aka 'unsigned long') [-Wsign-compare] 
+16
source

Source: https://habr.com/ru/post/947071/


All Articles