Why reimplement strlen as loop+subtraction?

Viewed 727

Inspired by this question about the following code from SQLite3:

 static int strlen30(const char *z){
    const char *z2 = z;
    while( *z2 ){ z2++; }
    return 0x3fffffff & (int)(z2 - z);
 }

that is accompanied by a commit message saying this function helps with int overflows.

I'm particularly interested in this part:

 const char *z2 = z;
 while( *z2 ){ z2++; }

to me this loop advances z2 until z2 points onto null terminator. Then z2-z yields the string length.

Why not use strlen() for this part and rewrite like this:

return 0x3fffffff & (int)(strlen(z));

Why use loop+subtraction instead of strlen()? What can loop+subtraction do what strlen() can't?

2 Answers
Related