Search code examples
c++cimplicit-conversionunsignedstrlen

Why does strlen in a if statement behave oddly?


#include <stdio.h>
#include <string.h>

int main()
{
    const char str[11]= "Hello World";
    if(-1 > strlen(str)){
        printf(str);
    }

    return 0;
}

This if condition should always return false. But here it's not. But if I put strlen(str) value to another variable and compare with that, then it works as expected. What I am missing here? Is it compiler dependent or something?


Solution

  • strlen returns an unsigned type.

    That has the effect of converting -1 to an unsigned type, which is a large number.

    That number will be greater than the strlen result so program control reaches the if statement body.

    If you assign the value of strlen to a variable of signed type, and compare using that, then the conversion of -1 will not occur and the if statement will behave as you expect.


    Note that technically the behaviour of your code is undefined, you need 12 elements for that string (for the NUL terminator), not 11, and strlen requires that NUL terminator in order to work properly. It's best to let the compiler do the counting, by writing

    const char str[] = "Hello World";