The following is excerpted from Writing solid code, page 115.
int strcmp( const char *strLeft, const char *strRight ) { for( NULL; *strLeft == *strRight; strLeft ++ ,strRight ++ ) if( strLeft == ‘\0’ ) return(0); return ( (*strLeft<*strRight)?-1:1 ); }The moment you use <, or any other operator that use sign information,
you force the compiler to generate nonprtable code
What does it(Bold line) mean? I know that
- right shifting sign integer is non-portable.
- comparing sign integer and unsigned integer is non-portable
Why is comparing two sign integer non-portable?
The ‘char’ type in C can be signed or unsigned. So here, if the strings are {0x81, 0} and {0x32, 0}, then if chars are signed 0x81 will be interpreted as a negative number (and the result will be that the first string compares less), and if chars are unsigned it’ll be interpreted as a positive number (so the second string will compare less). This is non-portable in the sense that the results differ based on the compiler you’ve used.