简体   繁体   中英

Short C Code: Confused strlen() function

My compiler: Dev C++ 5.3.0.3 TDM-GCC 4.6.1 64-bit My OS: Windows 7, 64bits

My C Code:

# include "stdio.h"
# include "string.h"

# define MAX (501)

int main() {
    char
        text[MAX]="";

    int i;

    i=0;
    printf("%d\n",strlen(text));        /* 0 */
    printf("%d\n",(strlen(text)-1));    /* -1 */
    if ( i<= (strlen(text)-1) ) printf("haha"); /* haha */

    return 0;
}

My question: Why "haha" is printed?! ( 0>-1 ?!!!) Thanks for your help!

strlen returns an unsigned value, and the comparison i < strlen(text) - 1 is performed for unsigned integers, in which 0 is indeed no larger than the other.

When dealing with unsigned types, it is far easier to reason about if you only use + :

if (i + 1 <= strlen(text))

Or even better:

if (i < strlen(text))

It can be a bit tricky to understand the arithmetic promotions and conversions for the built-in types and operators, and it might be worth reading up on those. There are certainly some unexpected situations. A good compiler can be made to warn you when you are comparing signed with unsigned types .

(If you're curious why in an expression with both signed and unsigned types both get promoted to unsigned, you may note that the conversion from signed to unsigned is absolutely well defined (via modular arithmetic), while the conversion from unsigned to signed is implementation-defined. I suppose that means that the promotion rules mean that the behaviour of arithmetic operations and comparisons is well-defined, rather than just implementation-defined.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM