gpt4 book ai didi

c - 变量(短)在复制/分配时更改值

转载 作者:太空宇宙 更新时间:2023-11-04 06:23:12 26 4
gpt4 key购买 nike

我有以下代码:

  short num_short = 1;
int possible_new_short = 1;
valid = 1;

while (valid) {
possible_new_short = num_short * 10;
printf("----\n");
printf("Num Short: %d\n", num_short);
printf("Possible New Short: %d\n", possible_new_short);
if (possible_new_short % 10 == 0) {
num_short = possible_new_short;
printf("New! %d\n", num_short);
} else {
valid = 0;
}
if (num_short == 0) {
valid = 0;
}
}
printf("num_short: %d\n", num_short);

输出如下:

----
Num Short: 1
Possible New Short: 10
New! 10
----
Num Short: 10
Possible New Short: 100
New! 100
----
Num Short: 100
Possible New Short: 1000
New! 1000
----
Num Short: 1000
Possible New Short: 10000
New! 10000
----
Num Short: 10000
Possible New Short: 100000
New! -31072
----

如您所见,possible_new_short 的值为 100000,但当重新分配给 num_short 时,它变为 -31072。为什么会这样?

我是 C 的新手,我猜是 num_short 变量溢出了。因为num_shortpossible_new_short存放在不同的内存槽中,一个可以溢出,一个不能?

有哪些最佳做法可以防止这种情况发生?

最佳答案

您的猜测是正确的,num_shortshort 类型,在当今大多数机器中通常是 16 位。

一个 16 位有符号整数最多可以容纳 215 − 1,即 32767。最后一个值 100000 溢出。

possible_new_short 不会溢出,因为它的类型是 int。通常,考虑变量持有的最大可能值,并相应地定义其类型。例如,您可以改用 long 甚至 long long

关于c - 变量(短)在复制/分配时更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30635139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com