Is it possible to write this flowchart into code without variables and goto?

萝らか妹 提交于 2019-12-23 07:02:57

问题


Is it possible to write this flowchart into C++ without variables and goto?

That's what I already have:

i1;
i2;
if(w1) {
    i3;
    while(w2) {
        i2;
        if(w1) { break; } // and it shouldn't do i4;
        i3;
    }
    i4;
}
i5;

回答1:


You can do it with some simple recursion. You have to be careful that your recursion has an appropriate "stop" condition to avoid a stack overflow.

Naming each "box" as a function, we get basically the following:

#include <iostream>
using namespace std;

void start_flowing();

int main()
{
   // This is the topmost "box"
   start_flowing();
   return 0;
}

void action_0();  // first "action" box
void check_0();   // first "decision" box
void action_1();  // second "action" box
void check_1();   // second "decision" box
void action_2();  // third "action" box
void complete();  // final "action" box

void start_flowing()
{
   // first box goes to second box directly
   action_0();
}

void action_0()
{
   // first action box goes to first decision directly
   check_0();
}

void check_0()
{
   // whatever this means...
   // this does the evaluation of the decision
   bool result = do_the_check();

   if(result)
   {
      // continue "down" to next action box
      action_1();
   }
   else
   {
      // short circuit out to completion
      complete();
   }
}

void action_1()
{
   check_1();
}

void check_1()
{
   // whatever this means...
   // this does the evaluation of the decision
   bool result = do_the_check();

   if(result)
   {
      // continue "down" to next action box
      action_2();
   }
   else
   {
      // jump back "up" to first action box
      action_0();
   }
}

void action_2()
{
   // completes the sequence
   complete();
}


来源:https://stackoverflow.com/questions/21582270/is-it-possible-to-write-this-flowchart-into-code-without-variables-and-goto

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