问题
When to use break, and continue in C language? Can I use them both with loop, and without loop? If a condition in a loop is enough to instruct whether to continue or not continue then what are the needs use them? Is it a good practice to use them?
Thanks in advance.
回答1:
Break,as the name suggests will break the execution of current loop once and for all while Continue will skip the execution of following statements and start new iteration.
It is known that loop may have it's termination condition, but sometimes it is possible that you achieve your goal before all the iteration has been executed (for example, consider best case scenario of Linear Search. It is possible that you found your element on 1st or 2nd iteration.)
In case of CONTINUE, sometimes it's possible that we need to skip some statement to get executed, but don't want to break the loop. (For example as given in the link, the requirement is to sum the positive elements of array.In this case you need to skip negative elements, which can be achieved by Continue keyword.)
Yes, you can use them both with loop and without loop (for i.e in if..else or else..if ladder).
And yes, it is certainly a good practice to use them as both can save lot of execution time according to requirements.
For more info: Click here and here
Hope it will help!!
回答2:
You might decide that the current loop iteration shouldn't run any more and want to start new iteration right away. This is what continue is for.
You also might decide that the whole loop shouldn't be running anymore, despite the loop condition could still evaluate to true. This is when break comes in handy.
来源:https://stackoverflow.com/questions/40080092/when-to-use-break-and-continue-in-c-language