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

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

考虑以下程序。

1)程序显示当我们越过“ char”范围时会发生什么:

<code>// 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;
} /<iostream>/<code>

这段代码会打印“ a”直到它变成226吗? 答案是不确定的循环,因为这里的“ a”被声明为字符,其有效范围是-128到+127。当“ a”通过a ++变为128时,超出范围,结果是该范围负数的第一个数字(即-128)分配给了a。因此,满足条件“ a <= 225”,并且控制保留在循环内。

2)程序显示当我们越过“bool”范围时会发生什么:

<code>// 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;
} /<iostream>/<code>

这段代码将无限次打印“ 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都是相同的数据类型。

<code>// 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;
} /<iostream>/<code>

该代码会一直打印“ a”直到变成32770吗? 答案是不确定的循环,因为这里的“ a”被声明为短整数,其有效范围是-32768至+32767。 当“ a”试图通过a ++变为32768时,超出范围,结果是该范围负数的第一个数字(即-32768)分配给了a。因此,条件“ a <32770”得到满足,控制仍在循环内。

4)程序显示当我们越过“unsigned short”范围时会发生什么:

<code>// 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;
} /<iostream>/<code>

这段代码会打印“ a”直到它变成65536吗? 答案是不确定的循环,因为这里的“ a”被声明为short,其有效范围是0到+65535。当“ a”尝试通过a ++变为65536时,超出范围,结果是范围中的第一个数字(即0)分配给了a。因此,条件“ a <65536”得到满足,控制仍在循环内。


分享到:


相關文章: