goto用法

goto:死循环用法

void CMamyTestDlg::OnBnClickedButton3()
{
failed:
    MessageBox(_T("跪了!"));

    CString s(_T("abcdef"));
    int nub = s.Find(_T("c"));
    if (nub> 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
    nub = s.Find(_T("x"));
    if (nub > 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
/*****************************************************
goto:放在函数头的情况下!!
      以下这个Find是不执行的,,因为上边goto failded,
  使函数又回头了函数头了,,goto failed == 递归回调自己
*****************************************************/
    nub = s.Find(_T("de"));
    if (nub > 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
}

goto:return用法

void CMamyTestDlg::OnBnClickedButton3()
{

    CString s(_T("abcdef"));
    int nub = s.Find(_T("c"));
    if (nub> 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
    nub = s.Find(_T("x"));
    if (nub > 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
/*****************************************************
goto:放在函数尾的情况下!!
      以下这个Find是不执行的,,因为上边goto failded,
  使函数已经走到了函数末尾了,,goto failed == return
*****************************************************/
    nub = s.Find(_T("de"));
    if (nub > 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
failed:
    MessageBox(_T("跪了!"));
}

goto:--> failed:正常语句执行了

void CMamyTestDlg::OnBnClickedButton3()
{
    CString s(_T("abcdef"));
    int nub = s.Find(_T("c"));
    if (nub> 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }

    nub = s.Find(_T("de"));
    if (nub > 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
failed:
    MessageBox(_T("跪了!"));
}
输出:
"找到了!"
"找到了!"
"跪了!"

goto: 普通用法(业余)

void CMamyTestDlg::OnBnClickedButton3()
{
    CString s(_T("abcdef"));
    int nub = s.Find(_T("c"));
    if (nub> 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }

    nub = s.Find(_T("de"));
    if (nub > 0)
    {
        MessageBox(_T("找到了!"));
    }
    else
    {
        goto failed;
    }
    return;
failed:
    MessageBox(_T("跪了!"));
}

goto: goto精髓应该不是这么用的,以后补充

当程序有多层嵌套,当处在嵌套内的逻辑判断为真或为假时,
需要彻底或者连续跳出几层循环时,一般考虑使用goto,
因为break一次只能跳出一层,
并且需要跳出多层循环时需要假如更多的判断逻辑,

你可能感兴趣的:(goto用法)