C # 루프-중단 대 계속
C # (다른 언어에 대해 자유롭게 대답 할 수 있음) 루프에서 루프의 구조를 떠나 다음 반복으로 이동하는 수단으로서 break와 continue의 차이점은 무엇입니까?
예:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
break
완전히 루프를 종료합니다 continue
단지 것이다 건너 뛸 현재 반복합니다.
예를 들면 :
for (int i = 0; i < 10; i++) {
if (i == 0) {
break;
}
DoSomeThingWith(i);
}
중단은 루프가 첫 번째 반복에서 종료되도록합니다 DoSomeThingWith
. 절대 실행되지 않습니다. 여기에 :
for (int i = 0; i < 10; i++) {
if(i == 0) {
continue;
}
DoSomeThingWith(i);
}
에 DoSomeThingWith
대해 실행되지 i = 0
않지만 루프는 계속 되고에 DoSomeThingWith
대해 실행 i = 1
됩니다 i = 9
.
이것을 이해하는 정말 쉬운 방법은 각 키워드 뒤에 "loop"라는 단어를 배치하는 것입니다. 이제 용어는 일상적인 문구처럼 읽 히면 의미가 있습니다.
break
루프-루프가 끊어지고 중지됩니다.
continue
loop-루프는 다음 반복으로 계속 실행됩니다.
break 는 프로그램 카운터가 가장 안쪽 루프의 범위를 벗어나도록합니다.
for(i = 0; i < 10; i++)
{
if(i == 2)
break;
}
이렇게 작동합니다
for(i = 0; i < 10; i++)
{
if(i == 2)
goto BREAK;
}
BREAK:;
루프의 끝으로 점프를 계속 합니다. for 루프에서 증가 표현식으로 계속 점프합니다.
for(i = 0; i < 10; i++)
{
if(i == 2)
continue;
printf("%d", i);
}
이렇게 작동합니다
for(i = 0; i < 10; i++)
{
if(i == 2)
goto CONTINUE;
printf("%d", i);
CONTINUE:;
}
휴식을 사용해야할지 계속해야할지 항상 혼란 스러웠습니다. 이것이 제가 기억하는 데 도움이되는 것입니다.
언제 중단과 계속을 사용합니까?
- Break- 헤어지는 것과 같습니다. 슬프다, 너희들이 헤어진다. 루프가 종료됩니다.
- 계속 -오늘 휴식을 취하고 내일 모든 것을 정리할 것임을 의미합니다 (즉, 현재 반복을 건너 뜁니다)!
break
foreach
루프를 완전히 중지하고 continue
다음으로 건너 뜁니다 DataRow
.
There are more than a few people who don't like break
and continue
. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-while
or do-until
style of loop.
I tend to use break
in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.
I use continue
when doing something with most elements of a list, but still want to skip over a few.
The break
statement also comes in handy when polling for a valid response from somebody or something. Instead of:
Ask a question
While the answer is invalid:
Ask the question
You could eliminate some duplication and use:
While True:
Ask a question
If the answer is valid:
break
The do-until
loop that I mentioned before is the more elegant solution for that particular problem:
Do:
Ask a question
Until the answer is valid
No duplication, and no break
needed either.
All have given a very good explanation. I am still posting my answer just to give an example if that can help.
// break statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // It will force to come out from the loop
}
lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
Here is the output:
0[Printed] 1[Printed] 2[Printed]
So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3
//continue statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // It will take the control to start point of loop
}
lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
Here is the output:
0[Printed] 1[Printed] 2[Printed] 4[Printed]
So 3[Printed] will not be displayed as there is continue when i == 3
Break
Break forces a loop to exit immediately.
Continue
This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.
By example
foreach(var i in Enumerable.Range(1,3))
{
Console.WriteLine(i);
}
Prints 1, 2, 3 (on separate lines).
Add a break condition at i = 2
foreach(var i in Enumerable.Range(1,3))
{
if (i == 2)
break;
Console.WriteLine(i);
}
Now the loop prints 1 and stops.
Replace the break with a continue.
foreach(var i in Enumerable.Range(1,3))
{
if (i == 2)
continue;
Console.WriteLine(i);
}
Now to loop prints 1 and 3 (skipping 2).
Thus, break
stops the loop, whereas continue
skips to the next iteration.
Ruby unfortunately is a bit different. PS: My memory is a bit hazy on this so apologies if I'm wrong
instead of break/continue, it has break/next, which behave the same in terms of loops
Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this
a = 5
while a < 10
a + 1
end
You can however do this
a = 5
b = while a < 10
a + 1
end # b is now 10
HOWEVER, a lot of ruby code 'emulates' a loop by using a block. The canonical example is
10.times do |x|
puts x
end
As it is much more common for people to want to do things with the result of a block, this is where it gets messy. break/next mean different things in the context of a block.
break will jump out of the code that called the block
next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.
def timesten
10.times{ |t| puts yield t }
end
timesten do |x|
x * 2
end
# will print
2
4
6
8 ... and so on
timesten do |x|
break
x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped
timesten do |x|
break 5
x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5
timesten do |x|
next 5
x * 2
end
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.
So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)
Simple answer:
Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)
Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.
for(int i = 0; i < list.Count; i++){
if(i == 5)
i = list.Count; //it will make "i<list.Count" false and loop will exit
}
다른 언어의 경우 :
'VB
For i=0 To 10
If i=5 then Exit For '= break in C#;
'Do Something for i<5
next
For i=0 To 10
If i=5 then Continue For '= continue in C#
'Do Something for i<>5...
Next
참고 URL : https://stackoverflow.com/questions/6414/c-sharp-loop-break-vs-continue
'developer tip' 카테고리의 다른 글
앱 스토어에서 앱에 연결하는 방법 (0) | 2020.09.30 |
---|---|
가장 유용한 속성 (0) | 2020.09.29 |
node.js에서 Base64 인코딩을 수행하는 방법은 무엇입니까? (0) | 2020.09.29 |
엄격한 앨리어싱 규칙은 무엇입니까? (0) | 2020.09.29 |
jQuery 비활성화 / 활성화 제출 버튼 (0) | 2020.09.29 |