为什么必须将用于保存 getchar 返回值的变量声明为 int? [英] Why must the variable used to hold getchar's return value be declared as int?

查看:31
本文介绍了为什么必须将用于保存 getchar 返回值的变量声明为 int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 语言的初学者,最近研究了 getchar 函数,它会接受来自控制台或文件的字符,输入时立即显示 我们需要按 Enter 键继续.

它返回他们读取的 unsigned char.如果遇到文件结束或错误getchar() 函数返回 EOF.

我的问题是,当它返回unsigned char时,为什么它的返回值存储在int变量中?

请帮帮我.

解决方案

正是因为那个 EOF 值.因为文件中的 char 可以是任何可能的 char 值,包括 C 字符串用于终止的空字符,getchar() 必须使用更大的整数类型来添加 EOF 值.>

它只是碰巧将 int 用于此目的,但它可以使用至少 9 位的任何类型.

I am beginner in C programming language, recently I have studied about getchar function, which will accept a character from the console or from a file, display it immediately while typing and we need to press Enter key for proceeding.

It returns the unsigned char that they read. If end-of-file or an error is encountered getchar() functions return EOF.

My question is that, When it returns unsigned char, then why its returned value is stored in int variable?

Please help me.

解决方案

Precisely because of that EOF-value. Because a char in a file may be any possible char value, including the null character that C-strings use for termination, getchar() must use a larger integer type to add an EOF-value.

It simply happens to use int for that purpose, but it could use any type with at least 9 bit.

这篇关于为什么必须将用于保存 getchar 返回值的变量声明为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆