當我們超過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”得到滿足,控制仍在循環內。


分享到:


相關文章: