如何使用函数来结束循环?

huangapple go评论63阅读模式
英文:

How to end a loop with a function?

问题

void Stop() {
    break;
}

int main() {

    while (true) {
        std::cout << "NO!" << '\n';
        Stop();
    }
    std::cout << "YES!";
}

在我的项目中,我需要使用一个函数来结束 while 循环,我该如何修改这个无法编译的示例?

我有一个使用 throw 的想法,但是否有其他更好的解决方案?


<details>
<summary>英文:</summary>

void Stop() {
break;
}

int main() {

while (true) {
	std::cout &lt;&lt; &quot;NO!&quot; &lt;&lt; &#39;\n&#39;;
	Stop();
}
std::cout &lt;&lt; &quot;YES!&quot;;

}

In my project I need to end `while` using a function, how can I change this uncompilable example?

I have an idea to use `throw`, but what about other better solutions?

</details>


# 答案1
**得分**: 4

你真的不能这样做。在**任何**编程语言中,使用异常来管理控制流和业务逻辑被认为是一种不良实践。你可以做的是,在循环中返回一个布尔标志以退出循环,例如,当此条件太复杂以直接编码在循环中时:

```cpp
bool Stop(int idx) {
    return idx > 10;
}

int main() {
    int counter = 0;
    while (true) {
        std::cout << "NO!" << '\n';
        const bool is_invalid = Stop(counter);

        if (is_invalid) break;
        ++counter;
    }
    std::cout << "YES!";
}
英文:

You can't really do this. Using exceptions for managing control flow and business logic is considered to be a bad practice in any programming language. What you can do, you could return a boolean flag for breaking out of the loop, for example, when this condition is too complex to be coded directly in the loop:

bool Stop(int idx) {
    return idx &gt; 10;
}

int main() {
    int counter = 0;
    while (true) {
        std::cout &lt;&lt; &quot;NO!&quot; &lt;&lt; &#39;\n&#39;;
        const bool is_invalid = Stop(counter);

        if (is_invalid) break;
        ++counter;
    }
    std::cout &lt;&lt; &quot;YES!&quot;;
}

答案2

得分: 3

这应该可以工作,但设计不够好。拿它作为一种示例,演示需要改变的部分以使其工作。

bool isRunning = false;

void Stop() {
    isRunning = false;
}

int main() {

    isRunning = true;

    while (isRunning) {
        std::cout << "NO!" << '\n';
        Stop();
    }
    std::cout << "YES!";
}
英文:

This should work, but it's not good design. Take it with a grain of salt, it's just to demonstrate what you need to change to make it work.

bool isRunning = false;

void Stop() {
    isRunnning = false;
}

int main() {

    isRunning = true;

    while (isRunning) {
        std::cout &lt;&lt; &quot;NO!&quot; &lt;&lt; &#39;\n&#39;;
        Stop();
    }
    std::cout &lt;&lt; &quot;YES!&quot;;
}

答案3

得分: 3

使该函数返回停止条件的值。我假设这只是一个简化的示例。在真实的示例中,该函数将接受参数,并且要么返回 true 要么返回 false(如果它总是无条件地停止循环,那么首先根本不需要循环,因此也不需要函数来停止循环):

bool Stop() {
    return false;
}

int main() {

    do  {
        std::cout << "NO!" << '\n';
    } while (Stop());
    std::cout << "YES!";
}
英文:

Make the function return the value of the stop condition. I suppose this is a simplified example. In a real example the function would take parameters and either return true or false (if it always stops the loop unconditionally, then there is no need for a loop in the first place, hence also no need for the function to stop the loop):

bool Stop() {
    return false;
}

int main() {

    do  {
        std::cout &lt;&lt; &quot;NO!&quot; &lt;&lt; &#39;\n&#39;;
    } while ( Stop() );
    std::cout &lt;&lt; &quot;YES!&quot;;
}

答案4

得分: 2

你可以通过对事物有控制来做类似的事情。

class Server {
public:
    Server() = default;
    
    void start() {
        loop();
    }
    
    
    void stop() {
        isRunning = false;
    }
    
private:
    void loop() {
        while (isRunning) {
            // 随时停止
        }
    }
    
private:
    bool isRunning = true;
};


int main() {
    Server sv;  
}
英文:

You can do something similar by having control over things.

class Server {
public:
    Server() = default;
    
    void start() {
        loop();
    }
    
    
    void stop() {
        isRunning = false;
    }
    
private:
    void loop() {
        while (isRunning) {
            // stop whenever you want
        }
    }
    
private:
    bool isRunning = true;
};


int main() {
    Server sv;  
}

答案5

得分: 0

你还可以使用一个布尔变量来实现无限循环,并通过某个函数的引用来更改它:

#include <iostream>

void Stop(bool& running) {
    running = false;
}

int main() {

    bool running = true;

    while (running) {
      // ...
      std::cout << "inside loop" << std::endl;
      Stop(running);
    }

    std::cout << "outside loop" << std::endl;
    return 0;
}
英文:

You can also use a bool variable for the infinite loop and change it by reference from some function:

#include &lt;iostream&gt;

void Stop(bool&amp; running) {
    running = false;
}

int main() {

    bool running = true;

    while (running) {
      // ...
      std::cout &lt;&lt; &quot;inside loop&quot; &lt;&lt; std::endl;
      Stop(running);
    }

    std::cout &lt;&lt; &quot;outside loop&quot; &lt;&lt; std::endl;
    return 0;
}

huangapple
  • 本文由 发表于 2023年1月9日 19:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定