吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C++教程 → C++ 中超出内置数据类型的有效范围时会发生什么?

C++ 中超出内置数据类型的有效范围时会发生什么?

来源:网络 | 更新时间:2022-02-11 07:44:07
考虑以下程序。  1) 显示当我们跨越 'char' 范围时会发生什么的程序: 
// C++ program to demonstrate
// the problem with 'char'
#include <iostream>

using namespace std;

int main()
{
for (char a = 0; a <= 225; a++)
cout << a;
return 0;
}
a 被声明为 char。这里循环从 0 到 225 工作。所以,它应该从 0 到 225 打印,然后停止。但它会产生一个无限循环。原因是字符数据类型的有效范围是 -128 到 127。当 'a' 通过 a++ 变为 128 时,超出范围,因此分配范围负数的第一个数字(即 -128)到一个。由于这个“a”永远不会到达点 225。所以它将打印无限系列的字符。 2) 显示当我们跨越 'bool' 范围时会发生什么的程序: 
// C++ program to demonstrate
// the problem with 'bool'
#include <iostream>

using namespace std;

int main()
{
// declaring Boolean
// variable with true value
bool a = true;

for (a = 1; a <= 5; a++)
cout << a;

return 0;
}
此代码将无限打印“1”,因为这里“a”被声明为“bool”,它的有效范围是 0 到 1。对于布尔变量,除 0 以外的任何值都是 1(或 true)。当“a”试图变成 2(通过 a++)时,1 被分配给“a”。满足条件 a<=5 并且控制保持在循环中。 3) 显示当我们跨越“short”范围时会发生什么的程序:  请注意,short 是 short int 的缩写。它们是同义词。short、short int、signed short 和 signed short int 都是相同的数据类型。 
// C++ program to demonstrate
// the problem with 'short'
#include <iostream>

using namespace std;

int main()
{
// declaring short variable
short a;

for (a = 32767; a < 32770; a++)
cout << a << "n";

return 0;
}
此代码会打印“a”直到变为 32770 吗?答案是无限循环,因为这里 'a' 被声明为 short 并且其有效范围是 -32768 到 +32767。当 'a' 试图通过 a++ 变为 32768 时,超出范围,结果范围负数的第一个数字(即 -32768)被分配给 a。因此,满足条件“a < 32770”并且控制保留在循环内。 4)程序显示当我们跨越“无符号短”范围时会发生什么: 
// C++ program to demonstrate
// the problem with 'unsigned short'
#include <iostream>

using namespace std;

int main()
{
unsigned short a;

for (a = 65532; a < 65536; a++)
cout << a << "n";

return 0;
}
这个代码会打印'a'直到它变成65536吗?答案是无限循环,因为这里 'a' 被声明为 short 并且其有效范围是 0 到 +65535。当 'a' 试图通过 a++ 变为 65536 时,超出了范围,因此范围中的第一个数字(即 0)被分配给 a。因此,满足条件“a < 65536”并且控制保留在循环内。 解释 –  我们知道计算机使用 2 的补码来表示数据。例如,如果我们有 1 个字节(我们可以使用 char 并使用 %d 作为格式说明符以将其视为十进制),我们可以表示 -128 到 127。如果我们将 1 与 127 相加,我们将得到 -128。那是因为 127 在二进制中是 01111111。如果我们将 1 加到 01111111 中,我们将得到 10000000。10000000 是 2 的补码形式的 -128。 如果我们使用无符号整数,也会发生同样的情况。255 是 11111111,当我们将 1 加到 11111111 时,我们将得到 100000000。但我们只使用前 8 位,所以这是 0。因此,在 255 中加 1 后得到 0。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com