Alternative way for goto statement in C++

扶醉桌前 提交于 2019-12-26 03:46:58

问题


Here's the link for the flowchart: http://i1146.photobucket.com/albums/o530/HTHVampire/C%20plus%20plus/Capture_zps5a6c3acf.jpg

Here's the code for the flowchart as shown, just ignore the ambiguous statement in the flowchart.

#include <iostream>
using namespace std;

int main()
{
    //declare and initialize a variable
    int a = 0;
    //prompt user for a value
    cout << "please enter a value" << endl;
    cin >> a;

    again1:
    //enter a decision block
    if(a > 10)
    {
        if(a < 10)
        {
            again2:
            if(a < 100)
            {
                a = a - 3;
                goto again2;
            }
            else goto again1;
        }
        else
        {
            a = a - 7;
            goto again1;
        }
    }
    else cout << "the output is " << a << endl;

    return 0;
}

May I know that can I play this code with if-else statement together with while statement? instead of goto statement.

Thanks for your guides!


回答1:


This structure should do the core logic according to the flowchart:

while (a > 10) {
    if (a < 10) {
        while (a < 100) {
            a += 3;
        }
    } else {
        a -= 7;
    }
}

Note that the if test is absurd. However, I didn't draw the flowchart; I just reproduced it in code.




回答2:


Nothing wrong with goto so long as you restrict use to state machines. Many teachers erroneously ban use of it for lack of understanding. For simple state machines like yours, and protocol decoding, it produces extremely readable code. I ruined years of embedded C routines because I was afraid to use goto.

I started using goto and my finger paintings turned into Van Gogh.



来源:https://stackoverflow.com/questions/17509953/alternative-way-for-goto-statement-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!