📌  相关文章
📜  当我们超出C++中的内置数据类型的有效范围时,会发生什么?

📅  最后修改于: 2021-05-25 20:44:05             🧑  作者: Mango

考虑以下程序。
1)程序显示当我们越过’char’范围时会发生什么:

CPP
// C++ program to demonstrate
// the problem with 'char'
#include 
 
using namespace std;
 
int main()
{
    for (char a = 0; a <= 225; a++)
        cout << a;
    return 0;
}


CPP
// C++ program to demonstrate
// the problem with 'bool'
#include 
 
using namespace std;
 
int main()
{
    // declaring Boolean
    // variable with true value
    bool a = true;
 
    for (a = 1; a <= 5; a++)
        cout << a;
 
    return 0;
}


CPP
// C++ program to demonstrate
// the problem with 'short'
#include 
 
using namespace std;
 
int main()
{
    // declaring short variable
    short a;
 
    for (a = 32767; a < 32770; a++)
        cout << a << "\n";
 
    return 0;
}


CPP
// C++ program to demonstrate
// the problem with 'unsigned short'
#include 
 
using namespace std;
 
int main()
{
    unsigned short a;
 
    for (a = 65532; a < 65536; a++)
        cout << a << "\n";
 
    return 0;
}


将a声明为char。此处循环从0到225工作。因此,它应从0到225打印,然后停止。但这会产生无限循环。原因是字符数据类型的有效范围是-128到127。当’a’通过a ++变为128时,该范围被超出,结果是从该范围的负数第一个数字(即-128)被分配了到结果,此“ a”将永远不会到达点225。因此它将打印出无限个字符序列。
2)程序显示当我们越过’bool’范围时会发生什么:

CPP

// C++ program to demonstrate
// the problem with 'bool'
#include 
 
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是short int的缩写。它们是同义词。 short,short int,signed short和signed short int都是相同的数据类型。

CPP

// C++ program to demonstrate
// the problem with 'short'
#include 
 
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)程序显示当我们跨过’unsigned short’的范围时会发生什么:

CPP

// C++ program to demonstrate
// the problem with 'unsigned short'
#include 
 
using namespace std;
 
int main()
{
    unsigned short a;
 
    for (a = 65532; a < 65536; a++)
        cout << a << "\n";
 
    return 0;
}
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”