Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using return to exit a loop?

Tags:

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()  {   for (int i = 1; i <= 100; i++)    {      if (i == 5)          **return;**      Console.WriteLine(i);     }    } } 

I know return can be used to exit if statements so I am curious about this as I have never tried it (and can't access my software to write the code to test this).

like image 538
GurdeepS Avatar asked Dec 01 '09 23:12

GurdeepS


People also ask

Does return exit a loop python?

break is used to end a loop prematurely while return is the keyword used to pass back a return value to the caller of the function. If it is used without an argument it simply ends the function and returns to where the code was executing previously.

How do you exit a loop?

Tips. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.

Is it good practice to return from inside a loop?

Yes, returning early is normally preferred rather than having to finish iterating over the entire collection when it's not needed, unless there's something else going on that warrants a complete iteration (finding the minimum/maximum value, etc.)


1 Answers

return will exit the current method (Main in your example). Use break to exit the loop.

like image 80
CesarGon Avatar answered Oct 19 '22 07:10

CesarGon