programing tip

(;;) 또는 while (true)의 올바른 C # 무한 루프는 무엇입니까?

itbloger 2020. 9. 2. 14:59
반응형

(;;) 또는 while (true)의 올바른 C # 무한 루프는 무엇입니까? [닫은]


C / C ++ 시절로 돌아가서 "무한 루프"를 다음과 같이 코딩했습니다.

while (true)

더 자연스럽고 더 분명해 보였습니다.

for (;;)

1980 년대 후반 PC-lint 와의 만남 과 그에 따른 모범 사례 논의는이 습관을 깨뜨 렸습니다. 이후 for제어문을 사용하여 루프를 코딩했습니다 . 오늘, 오랜만에 처음으로 그리고 아마도 C # 개발자로서 처음으로 무한 루프가 필요한 상황에 처해 있습니다. 그들 중 하나는 정확하고 다른 하나는 맞지 않습니까?


while(true)
{

}

항상 내가 사용한 것과 다른 사람들이 수동으로 끊어야하는 루프에 사용하는 것을 본 것입니다.


C # 컴파일러는

for(;;)
{
    // ...
}

while (true)
{
    // ...
}

으로

{
    :label
    // ...
    goto label;
}

둘 다에 대한 CIL은 동일합니다. 대부분의 사람들 while(true)은 읽고 이해하기가 더 쉽습니다. for(;;)다소 비밀 스럽습니다.

출처:

.NET Reflector를 조금 더 사용 하고 Visual Studio에서 "Optimize Code"를 사용하여 두 루프를 모두 컴파일했습니다.

두 루프 모두 다음으로 컴파일됩니다 (.NET Reflector 사용) :

Label_0000:
    goto Label_0000;

랩터는 곧 공격해야합니다.


나는 이것이 더 읽기 쉬울 수 있고 확실히 C #에서 사용하는 표준이라고 생각합니다.

while(true)
{
   //Do My Loop Stuff
}

헐떡이고, 사용 :

while (!false)
{

}

또는 jsight가 지적했듯이 두 배로 확신 할 수 있습니다.

while (!false && true)
{
}

사람들이 나에게 소리를 지르기 전에 모두 동일한 CIL 코드입니다. :)


몇 가지 오래된 농담을 다시 해보려면 :

  1. " for (;;) {}"을 (를) 사용하지 마십시오 . 이는 진술을 울립니다.
  2. 물론 " #define EVER ;;"이 아니라면 .

구식으로 가고 싶다면 C #에서 goto가 계속 지원됩니다.

STARTOVER:  
    //Do something
    goto STARTOVER;

For a truly infinite loop, this is the go-to command. =)


I think while (true) is a bit more readable.


In those situations where I needed a true infinite loop, I've always used

while(true) {...}

It seems to express intent better than an empty for statement.


Personally, I have always preferred for(;;) precisely because it has no condition (as opposed to while (true) which has an always-true one). However, this is really a very minor style point, which I don't feel is worth arguing about either way. I've yet to see a C# style guideline that mandated or forbade either approach.


I personally prefer the for (;;) idiom (coming from a C/C++ point of view). While I agree that the while (true) is more readable in a sense (and it's what I used way back when even in C/C++), I've turned to using the for idiom because:

  • it stands out

I think the fact that a loop doesn't terminate (in a normal fashion) is worth 'calling out', and I think that the for (;;) does this a bit more.


The original K&R book for C, from which C# can trace its ancestry, recommended

for (;;) ...

for infinite loops. It's unambiguous, easy to read, and has a long and noble history behind it.

Addendum (Feb 2017)

Of course, if you think that this looping form (or any other form) is too cryptic, you can always just add a comment.

// Infinite loop
for (;;)
    ...

Or:

for (;;)    // Loop forever
    ...

It should be while(true) not while(1), so while(1) is incorrect in C#, yes ;)


Alternatively one could say having an infinite loop is normally bad practice anyway, since it needs an exit condition unless the app really runs forever. However, if this is for a cruise missile I will accept an explicit exit condition might not be required.

Though I do like this one:

for (float f = 16777216f; f < 16777217f; f++) { } 

I prefer slightly more "literate" code. I'm much more likely to do something like this in practice:

bool shouldContinue = true;
while (shouldContinue)
{
    // ...

    shouldContinue = CheckSomething();
}

Even I also say the below one is better :)

while(true)
{

}

If you're code-golfing, I would suggest for(;;). Beyond that, while(true) has the same meaning and seems more intuitive. At any rate, most coders will likely understand both variations, so it doesn't really matter. Use what's most comfortable.


The only reason I'd say for(;;) is due the CodeDom limitations (while loops can't be declared using CodeDom and for loops are seen as the more general form as an iteration loop).

This is a pretty loose reason to choose this other than the fact that the for loop implementation can be used both for normal code and CodeDom generated code. That is, it can be more standard.

As a note, you can use code snippets to create a while loop, but the whole loop would need to be a snippet...


Both of them have the same function, but people generally prefer while(true). It feels easy to read and understand...


Any expression that always returns true should be OK for while loop.

Example:

1==1 //Just an example for the text stated before 
true

In terms of code readability while(true) in whatever language I feel makes more sense. In terms of how the computer sees it there really shouldn't be any difference in today's society of very efficient compilers and interpreters.

If there is any performance difference to be had I'm sure the translation to MSIL will optimise away. You could check that if you really wanted to.

참고URL : https://stackoverflow.com/questions/1401159/which-is-the-correct-c-sharp-infinite-loop-for-or-while-true

반응형