Aren't ASCII values of 'a' to 'z&#

2019-05-14 06:13发布

问题:

This question already has an answer here:

  • Who determines the ordering of characters 6 answers

I see nothing wrong with the following program, and this being non-portable is really confusing to me. According to the book by Mike Banahan (GBdirect C Book, Section 2.4.2), the following program is non-portable. Reason given is:

Another example, perhaps. This will either print out the whole lower case alphabet, if your implementation has its characters stored consecutively, or something even more interesting if they aren't. C doesn't make many guarantees about the ordering of characters in internal form, so this program produces non-portable results!

So, in simple terms, can you explain me what's wrong with the below program? Aren't the ASCII values of characters same irrespective of implementation? I mean, value of 'a' is always 97 and that of 'b' is always 98; so why is getting the latter by adding 1 non-portable?

#include <stdio.h>
#include <stdlib.h>
main(){
      char c;

      c = 'a';
      while(c <= 'z'){
              printf("value %d char %c\n", c, c);
              c = c+1;
      }

      exit(EXIT_SUCCESS);
}

回答1:

C doesn't require ASCII encoding. It allows other encodings, some of which may not have letters represented by consecutive values.

An example is EBCDIC where letters are not consecutive.

Note that the characters for digits are guaranteed by the C standard to always be consecutive (although they may not have values 48-57 as in ASCII).