Aren't ASCII values of 'a' to 'z' consecutive from 97 to 122 irrespective of implementation? A good book says otherwise [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 12:00:47

问题


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).



来源:https://stackoverflow.com/questions/25833439/arent-ascii-values-of-a-to-z-consecutive-from-97-to-122-irrespective-of-imp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!