I've written the following code to reverse a string in C. The code seems to works properly and that's why I'm confused. Does anyone know why there is not an error here? I was expecting an array out of bounds or an infinite loop on the for loop, but it seems the loop breaks before it gets to 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;
}
size_t is generally defined as unsigned. When you compare a signed and an unsigned number or equal rank the signed number is converted to unsigned. Since the signed number is probably represented in two's complement in your machine negative numbers are actually larger.
So once i
hits -1, it is larger the comparison thinks its larger than len.
You can see this is happening by turning on 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With