简体   繁体   English

使用int变量作为char变量可以吗?

[英]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. 另一方面, 指向 intchar 指针 不可互换。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM