[英]is using int variables as char variables OK?
so my question is why do some people use int variables as char variables. 所以我的问题是为什么有些人将int变量用作char变量。 exemple
例子
int main()
{
int i;
scanf("%c",&i);
printf ("%c",i);
}
thank's in advance 提前致谢
C's char
is an integer type. C的
char
是整数类型。 Its (numeric) values are most often used to represent characters, but that's a separate matter. 它的(数字)值最常用于表示字符,但这是另一回事。
You can safely use a variable of type int
to hold a value in the range of type char
. 您可以安全地使用
int
类型的变量来保存char
类型范围内的值。 You can assign a char
to an int
or pass a char
to a function expecting an int, both without a cast and without altering the value. 您可以将
char
分配给int
或将char
传递给需要int
的函数,而无需强制转换和更改值。
In certain places, int
is used intentionally instead of char
to represent characters. 在某些地方,有意使用
int
代替char
来表示字符。 The canonical case is probably the standard library's getc()
, fgetc()
, and getchar()
functions, which need the range of an int
to be able to represent EOF
in addition to every possible char
value. 规范的情况可能是标准库的
getc()
, fgetc()
和getchar()
函数,除了每个可能的char
值之外,它们还需要一个int
的范围才能表示EOF
。 Also, for historical reasons, some other functions declare int
arguments to accept data expected to be of type char
; 同样,出于历史原因,其他一些函数声明
int
参数以接受预期为char
类型的数据; memset()
is one of the better known of these. memset()
是其中比较知名的一种。
On the other hand, pointers to int
and to char
are not interchangeable. 另一方面, 指向
int
和char
指针 不可互换。 As others pointed out, your scanf()
call produces undefined behavior for that reason. 正如其他人指出的,由于这个原因,您的
scanf()
调用会产生未定义的行为。
Generally speaking, you should use char
rather than int
to represent character data, unless there is a good, externally-driven reason to do otherwise (such as needing to handle the return value of getchar()
). 一般来说,除非有充分的外部驱动原因(例如需要处理
getchar()
的返回值getchar()
,否则应使用char
而不是int
来表示字符数据。 Even more generally speaking, match data types correctly, being deliberate about where you allow type conversions to be performed. 更一般地说,正确地匹配数据类型,仔细考虑允许在哪里执行类型转换。
This - 这个 -
scanf("%c",&i);
Wrong argument is passed ( %c
expects address of char ).It invokes undefined behaviour . 传递了错误的参数(
%c
需要char的地址)。它将调用未定义的行为 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.