c语言定义求助
这是一道课后题5. 为什么小甲鱼说 getchar() 返回值为 int 是为了存放 EOF,而 EOF 通常被定义为 -1,char 类型即可存放,为啥还要 int 类型?
答:因为 char 默认定义为 unsigned char 还是 signed char 是取决于编译系统,所以 char 在某些编译系统可能无法存放负数;而 int 默认是 signed int。
我突然脑洞大开的认为既然默认的不一样,那定义 get char 函数的时候在前面加一个signed 前缀不就好了吗?(求大佬指点)
历史遗留问题 #include <stdio.h>
/* copy input to output; 2nd version */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
}
在键盘或者屏幕上的字符都是用 char 类型存储的,当然也可以用 int 类型来存储。这个地方使用 int 来存储字符有一个微妙但很重要的原因:为了把有效数据和输入的结束(EOF)区分开来。getchar() 在没有更多输入数据时返回一个特殊值,这个值不会跟任何实际的字符混淆。这个值称为 EOF(end of file,文件结束)。我们必须把 c 变量声明成一个大到足够存储任何 getchar() 返回的值的类型。我们不能用 char 类型,因为 c 必须大到足够容纳任意可能的 char 还有 EOF。因此我们使用 int 类型。
C语言中 getchar() 的函数声明:
int getchar ( void );
返回值是int,在Linux下输入命令:man getchar(),结果更加详细:
NAME
fgetc, fgets, getc, getchar, gets, ungetc - input of characters and strings
[…]
DESCRIPTION
fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on
end of file or error.
getchar()从标准输入(stdin)流中读取一个字符,把它当作一个 unsigned char,然后强制转化成 int 类型来做为返回值,如果遇到文件末尾或者错误,返回EOF。
更详细的说明看这里:https://www.cnblogs.com/3me-linux/p/4121465.html
getchar() 是一个已经定义了的函数,函数的类型由返回值确定,故不能在其前面加 signed 来定义其类型
页:
[1]