📜  C ++失败

📅  最后修改于: 2021-05-31 16:42:22             🧑  作者: Mango

失败是一种错误类型,它发生在各种编程语言中,例如C C++ Java Dart …等。它发生在switch-case语句中,当我们忘记添加break语句时,控制流会跳到下一行。因此,当任何情况与指定值匹配时,控制权将转移到后续情况,直到找到break语句为止。在C++中,未对下通但在样Dart语言中的错误,无论何时发生下通发生错误。

并非总是需要避免失败,但是它也可以用作优点。

程序1:

下面的程序说明了失败的发生方式:

C++
// C++ program to illustrate
// Fallthrough in C++
#include 
using namespace std;
  
// Driver Code
int main()
{
    int n = 2;
  
    // Switch Cases
    switch (n) {
    case 1: {
        cout << "this is one \n";
    }
    case 2: {
        cout << "this is two \n";
    }
    case 3: {
        cout << "this is three \n";
    }
    default: {
        cout << "this is default \n";
    }
    }
  
    return 0;
}


C++
// C++ program to illustrate how to
// avoid fall through
#include 
using namespace std;
  
// Driver Code
int main()
{
    int n = 2;
  
    // Switch Cases
    switch (n) {
    case 1: {
        cout << "this is one \n";
        break;
    }
  
    case 2: {
        cout << "this is two \n";
  
        // After this break statement
        // the control goes out of
        // the switch statement
        break;
    }
    case 3: {
        cout << "this is three \n";
        break;
    }
    default: {
        cout << "this is default \n";
        break;
    }
    }
  
    return 0;
}


输出:
this is two 
this is three 
this is default

说明:在上面的代码中,没有break语句,因此在与第二种情况匹配后,控件将掉线,随后的语句也将被打印。

如何避免跌倒?

为了避免掉线,我们的想法是在每种情况下都使用break语句,以便在匹配后将其移出switch语句,而控制权转到switch语句旁边的语句。

程式2:

下面是说明如何避免失败的程序:

C++

// C++ program to illustrate how to
// avoid fall through
#include 
using namespace std;
  
// Driver Code
int main()
{
    int n = 2;
  
    // Switch Cases
    switch (n) {
    case 1: {
        cout << "this is one \n";
        break;
    }
  
    case 2: {
        cout << "this is two \n";
  
        // After this break statement
        // the control goes out of
        // the switch statement
        break;
    }
    case 3: {
        cout << "this is three \n";
        break;
    }
    default: {
        cout << "this is default \n";
        break;
    }
    }
  
    return 0;
}
输出:
this is two
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”