title: Is the strcasecmp algorithm flawed?
body: <p>I am trying to reimplement the <code>strcasecmp</code> function in C and I noticed what appears to be an inconsistency in the comparison process.</p>
  
  <p>From <code>man strcmp</code></p>
  
  <blockquote>
    <p>The strcmp() function compares the two strings s1 and s2. The locale is not taken into account (for a locale-aware comparison, see strcoll(3)).
    It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.</p>
  </blockquote>
  
  <p>From <code>man strcasecmp</code></p>
  
  <blockquote>
    <p>The strcasecmp() function performs a byte-by-byte comparison of
    the strings s1 and s2, ignoring the case of the characters. It returns
    an integer less than, equal to, or greater than zero if s1 is found,
    respectively, to be less than, to match, or be greater than s2.</p>
  </blockquote>
  
  <p><code>int strcmp(const char *s1, const char *s2);</code><br>
  <code>int strcasecmp(const char *s1, const char *s2);</code></p>
  
  <p>Given, this information, I don't understand the result of the following code:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int main()
  {
      // ASCII values
      // 'A' = 65
      // '_' = 95
      // 'a' = 97
  
      printf("%i\n", strcmp("A", "_"));
      printf("%i\n", strcmp("a", "_"));
      printf("%i\n", strcasecmp("A", "_"));
      printf("%i\n", strcasecmp("a", "_"));
      return 0;
  }
  
  </code></pre>
  
  <p>Ouput:</p>
  
  <pre class="lang-sh prettyprint-override"><code>-1  # "A" is less than "_"
  1   # "a" is more than "_"
  2   # "A" is more than "_" with strcasecmp ???
  2   # "a" is more than "_" with strcasecmp
  </code></pre>
  
  <p>It appears that, if the current character in <code>s1</code> is a letter, it is always converted to lowercase, regardless of whether the current character in <code>s2</code> is a letter or not.</p>
  
  <p>Can someone explain this behaviour? Shouldn't the first and third lines be identical?</p>
  
  <p>Thank you in advance!</p>
  
  <p>PS:<br>
  I am using <code>gcc 9.2.0</code> on Manjaro.<br>
  Also, when I compile with the <code>-fno-builtin</code> flag I get instead:</p>
  
  <pre class="lang-sh prettyprint-override"><code>-30
  2
  2
  2
  </code></pre>
  
  <p>I guess it's because the program does not use gcc's optimised functions, but the question remains.</p>