“strlen(s1) - strlen(s2)” is never less than zero

后端 未结 3 1507
礼貌的吻别
礼貌的吻别 2020-12-04 10:56

I am currently writing a C program that requires frequent comparisons of string lengths so I wrote the following helper function:

int strlonger(char *s1, cha         


        
3条回答
  •  无人及你
    2020-12-04 11:49

    Alex Lockwood's answer is the best solution (compact, clear semantics, etc).

    Sometimes it does make sense to explicitly convert to a signed form of size_t: ptrdiff_t, e.g.

    return ptrdiff_t(strlen(s1)) - ptrdiff_t(strlen(s2)) > 0;
    

    If you do this, you'll want to be certain that the size_t value fits in a ptrdiff_t (which has one fewer mantissa bits).

提交回复
热议问题