[英]Why (char) + (char) = (int) in C?
Is it for the same reason as char + char = int?与char + char = int的原因相同吗? Why?
为什么? ?
?
I got different results on this source code by different compilers不同的编译器在这个源代码上得到了不同的结果
#include <stdio.h>
int main() {
char a = 100, b = 100;
printf("%d\n", a + b);
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
}
You get different results because scanf("%d%d", &a, &b)
is incorrect.您会得到不同的结果,因为
scanf("%d%d", &a, &b)
不正确。 For each %d
, scanf
expects the address of an int
object, but you provided the addresses of char
objects.对于每个
%d
, scanf
需要一个int
object 的地址,但您提供了char
对象的地址。 This results in (dangerous) undefined behaviour.这会导致(危险的)未定义行为。
For char
objects, use the following:对于
char
对象,请使用以下内容:
scanf("%hhd%hhd", &a, &b) // In a environment with signed chars
-or-
scanf("%hhu%hhu", &a, &b) // In a environment with unsigned chars
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.