Houxiong Yao
Houxiong Yao

Reputation: 19

Why is "-1 < strlen(s)" equal to 0?

char* s =(char*) "sss";
int j = -1;
printf("%d", j < strlen(s));

It's mainly about the difference between j < 3 and j < strlen(s).

In the above code, the printf() function prints 0, but if I change strlen(s) to 3, the result becomes 1 (just as what I expect).

What is the cause?

Upvotes: -1

Views: 166

Answers (2)

Tom Karzes
Tom Karzes

Reputation: 24102

The return type of strlen is size_t, which is an unsigned integer type. When comparing a size_t to an int, the "usual arithmetic conversions" are applied. In this case, that means the int operand, i.e. -1, is converted to a size_t, resulting in the largest possible size_t value, which is greater than the strlen value.

Upvotes: 8

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

In this expression

j < strlen(s)

the compiler at first determines the common type of the expression to perform the operation using the usual arithmetic conversions.

The type of the expression strlen( s ) is unsigned integer type size_t that usually is defined as an alias for the type unsigned long.

From the C Standard (6.3.1.8 Usual arithmetic conversions):

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. See the declaration of the function strlen

size_t strlen(const char *s);
^^^^^^

As the rank of the type size_t is greater than the rank of the signed type int then the left operand of the comparison operator is converted to the type size_t propagating the sign bit. As a result you get a very big unsigned value.

Try for example this call of printf

printf( "( size_t )-1 = %zu\n", ( size_t )-1 );

Upvotes: 4

Related Questions