Note that there are some explanatory texts on larger screens.

plurals
  1. POstrcmp() and signed / unsigned chars
    primarykey
    data
    text
    <p>I am confused by strcmp(), or rather, how it is defined by the standard. Consider comparing two strings where one contains characters outside the ASCII-7 range (0-127). </p> <p>The C standard defines:</p> <blockquote> <p><strong>int strcmp(const char *s1, const char *s2);</strong></p> <p>The strcmp function compares the string pointed to by s1 to the string pointed to by s2.</p> <p>The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.</p> </blockquote> <p>The parameters are <strong><code>char *</code></strong>. Not <strong><code>unsigned char *</code></strong>. There is no notion that "comparison should be done as <code>unsigned</code>".</p> <p>But all the standard libraries I checked consider the "high" character to be just that, <em>higher</em> in value than the ASCII-7 characters.</p> <p>I understand this is useful and the expected behaviour. I don't want to say the existing implementations are wrong or something. I just want to know, <strong>which part in the standard specs have I missed</strong>?</p> <pre><code>int strcmp_default( const char * s1, const char * s2 ) { while ( ( *s1 ) &amp;&amp; ( *s1 == *s2 ) ) { ++s1; ++s2; } return ( *s1 - *s2 ); } int strcmp_unsigned( const char * s1, const char *s2 ) { unsigned char * p1 = (unsigned char *)s1; unsigned char * p2 = (unsigned char *)s2; while ( ( *p1 ) &amp;&amp; ( *p1 == *p2 ) ) { ++p1; ++p2; } return ( *p1 - *p2 ); } #include &lt;stdio.h&gt; #include &lt;string.h&gt; int main() { char x1[] = "abc"; char x2[] = "abü"; printf( "%d\n", strcmp_default( x1, x2 ) ); printf( "%d\n", strcmp_unsigned( x1, x2 ) ); printf( "%d\n", strcmp( x1, x2 ) ); return 0; } </code></pre> <p>Output is:</p> <pre><code>103 -153 -153 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload