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

考虑下面的程序。 1) 程序显示当我们跨越“字符”范围时会发生什么:

null

CPP

// 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。因此,“a”永远不会到达点225。所以它会打印出无限系列的字符。 2) 程序显示当我们越过“bool”范围时会发生什么:

CPP

// 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,控制保持在回路中。看见 对于Bool数据类型。 3) 程序显示当我们越过“短”范围时会发生什么: 注意short是short int的缩写,它们是同义词。short、short int、signed short和signed short int都是相同的数据类型。

CPP

// 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 << "" ;
return 0;
}


这个代码会打印“a”直到变成32770吗?答案是不确定循环,因为这里“a”被声明为短循环,其有效范围是-32768到+32767。当“a”试图通过a++变为32768时,超出范围,因此范围负端的第一个数字(即-32768)被分配给a。因此满足条件“a<32770”,控制仍在循环内。 4) 程序显示当我们跨越“无符号短线”范围时会发生什么:

CPP

// 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 << "" ;
return 0;
}


这个代码会打印“a”直到变成65536吗?答案是不确定循环,因为这里“a”被声明为短循环,其有效范围是0到+65535。当“a”试图通过a++变为65536时,超出范围,因此范围中的第一个数字(即0)被分配给a。因此,满足条件“a<65536”,控制仍在循环中。 解释—— 我们知道计算机用2的补码来表示数据。例如,如果我们有1个字节(我们可以使用char并使用%d作为格式说明符将其视为十进制),我们可以表示-128到127。如果我们把1和127相加,我们将得到-128。这是因为127在二进制中是0111111。如果我们在01111111中加1,我们将得到10000000。10000000是2的补码形式的-128。 如果我们使用无符号整数,也会发生同样的情况。255是11111111当我们把1加到11111111时,我们将得到100000000。但我们只使用前8位,所以是0。因此,在255中加1后,我们得到0。 本文由 阿迪提亚·拉赫查 并通过 萨希·提瓦里 如果你喜欢Geeksforgek,并且想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享