[英]Practical difference between int and char
I have to analyse the output of these code fragments: 我必须分析这些代码片段的输出:
int x, y;
x = 200; y = 100;
x = x+y; y = x-y; x = x-y;
printf ("%d %d\n", x, y);
char x, y;
x = 200; y = 100;
x = x+y; y = x-y; x = x-y;
printf ("%d %d\n", x, y);
So, I know now that int
stands for integer and char
for character; 所以,我现在知道
int
代表整数, char
代表字符; I've read about the differences and if I put in the printf
the %d
, it returns in the form of digits, and %c
, in the form of a character. 我已经阅读了差异,如果我在
printf
输入%d
,它会以数字的形式返回,而%c
则以字符的形式返回。
The ASCII character code for 'A'
is 65 for example, but why does the second function print 100 -56
, instead of 100 200
? 例如,
'A'
的ASCII字符代码是65,但为什么第二个函数打印100 -56
而不是100 200
?
C has a variety of integer types: char
(at least 8 bits), short
(at least 16 bits), int
(at least 16 bits), long
(at least 32 bits). C有多种整数类型:
char
(至少8位), short
(至少16位), int
(至少16位), long
(至少32位)。 There are unsigned
varieties of those. 有
unsigned
品种。 If you assign a value that is too large to a plain type, the results are undefined (you should never do that, the compiler may assume you never do, and not check at all). 如果为普通类型分配的值太大,则结果是未定义的(您永远不应该这样做,编译器可能会假设您从未这样做,而根本不检查)。 In the
unsigned
case, they "wrap around". 在
unsigned
情况下,他们“环绕”。 But note that the sizes are not guaranteed , just their minimal sizes. 但请注意,尺寸不能保证 ,只是它们的最小尺寸。 There have been machines in which all were 32 bits wide.
有些机器都是32位宽。
On the platform used in the question, the type char
seems to be 1 byte (8 bits) size and is a signed type with 1 sign bit and 7 value bits (and using 2's complement arithmetic). 在问题中使用的平台上,
char
类型似乎是1字节(8位)大小,并且是带有1个符号位和7个值位(并使用2的补码算术)的带符号类型。 It stores values from -128 to 127. So, this is what's happening to x
and y
: 它存储从-128到127的值。因此,这是
x
和y
发生的情况:
x = 200 => x takes value -56
y = 100 => y takes value 100
x = x+y => x takes value 44
y = x-y => y takes value -56
x = x-y => x takes value 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.