Using return to exit a loop?

后端 未结 5 1205
悲哀的现实
悲哀的现实 2021-01-07 18:27

If I write a for, do, or while loop, is it possible to come out of this with the return keyword?

Eg:

class BreakTest 
{
public static void Main() 
{
         


        
5条回答
  •  囚心锁ツ
    2021-01-07 19:07

    You can do this. Calling return; will exit Main(). Normally you'd use break; to break out of the for loop instead.

    That being said, it's often considered bad practice to have multiple return locations within a single function. Many developers prefer to have a single return statement (if the method isn't declared with void). This can make the code more easy to follow, from an understandability point of view, and hence easier to maintain and test.

提交回复
热议问题