int c = getchar()?

后端 未结 6 1911
予麋鹿
予麋鹿 2020-11-27 15:20

ok so im reading this book: The C Programming Language - By Kernighan and Ritchie (second Edition) and one of the examples im having trouble understanding how things are wor

6条回答
  •  萌比男神i
    2020-11-27 15:41

    Now let's play a game of logic.

    Char is also a type of integer which has a smaller range than int, more specifically 8 bits, that is, 1 byte. As we all know, integer types consists of signed ( default ) and unsigned. As for char, the range of signed is -127 ~ 128 and the range of unsigned is 0 ~ 255. Now we know the type and "capability" of signed and unsigned char.

    We human understand characters while the computer recogonize only binary sequence. Thus all kinds of programming language must provode a model to deal with the cevertion from characters to binary sequence. ASCII code is the standard for the mapping which applied in C and many other programming languages. It takes 0 - 255 to code basic characters like 0-9, a-z and A-Z, as well as usual special ones.

    You may wonder that unsigned char is the exact choice. However, the progamming should know when to stop. The simplest way is to meet a special value, a negative one is a good choice since bigger positive values might be used for other languages. Finally, C choosed -1, which is more commonly called EOF.

    Now we've got the point. Signed char will not suffice to code ASCII characters while unsigned leaves no room for the termination value. We require a larger range to balace this, that is, the int type. Savy?

    Thanks for the answer of @cdhowie, it acually kindled me.

提交回复
热议问题