Search code examples
c++expressionboolean-expressionstrlen

Strange behavior w/ strlen() in boolean expression


Today I was trying to debug an application and I found a strange behavior of a boolean expression that contains strlen().

Here follows a simple code that reproduces the issue.

char test[20] = "testTestTest";  //the length is 12
bool b = 0 < (9 - strlen(test)); //should be false (0 < -3) = false

at the end of the execution b is true but it should be false.

Saving the result of strlen() in a variable works.

char test[20] = "testTestTest"; //the length is 12
int length = strlen(test);      //save the length
bool b = 0 < (9 - length);      //should be false (0 < -3) = false

at the end of the execution b is false (as it is supposed to be).

What is the difference between the two implementations?
Why is the first one not working?

The original affected code was something like this:

char test[20] = "testTestTest"; //the length is 12
for(int i = 0; i < (9 - strlen(test)); i++){
    //do something (in my case I do NOT edit the test string)
}

the for loop is supposed to be never executed (with strings >= 9) but it actually loops infinitely.


Solution

  • Saving the result of strlen() in a variable works.

    Your variable is of a different type than what strlen() returns. It's the implicit conversion from size_t to int that makes it work.

    The non-working version typically evaluates 9 - strlen(test) as (size_t)9 - strlen(test), a very large unsigned number, rather than as 9 - (int)strlen(test), a negative signed number.