Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char Array - Why for loop is not infinite?

Tags:

c

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;
}
like image 767
sager89 Avatar asked Jun 12 '13 03:06

sager89


1 Answers

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]
like image 162
FDinoff Avatar answered Nov 09 '22 08:11

FDinoff