- 1
What is break; in c#, and what purpose does it serve(Explain it to me as if i'm an idiot plz).
// and can you even explain what it does in this code. int num = 0; while (num < 20) { if (num == 5) break; Console.WriteLine(num); num++; }
5 ответов
+ 8
In your example:
The loop runs and num gets incremented for each loop, i.e. values of num increases from 0 to 1, 2, 3...
When num is 5, it fulfills the if conditional statement and break is executed.
What break does is to tell the program flow to "break" out of the loop which it is currently in. When the break statement is encountered, the while loop will be exited directly. Hence, num (5) will not be printed to the console because the print statement comes after the break, and is inside the while loop. The program exits the loop before num can get printed.
+ 4
as long as when num is below 20, test if num is 5. If num is 5, stop the loop. else write down the value of num and add the value of num by 1
break; == exit/stop any loop
+ 2
Thanks Hasty Rei, I kinda get it now. So I'll will just move on to more lessons and eventually i will pick onto it
0
break; basically jumps out of the loop, in this case, the while loop. this can be put in other loops like for loops etc.
0
Okay, if you don't mind can you give a better example and definition of break; ,and explain step by step what break does to the code.