Yes:
this loop is like infinity loop
You're correct in that while(true)
is an instruction to loop forever.
However, there are a few other ways to exit loops:
- A
return
statement will exit the function (and consequently also terminate the loop) - A
break
statement will exit the closestfor
,while
orswitch
statement. - A
goto
statement might cause the code to jump to a label outside the loop - An
exit()
call will cause the whole program to terminate. - A
throw
statement will throw an exception that will break out to the nearest appropriatecatch
statement (which might be outside the loop).
In this case, the return;
near the bottom of the loop causes the function to exit.
The break;
statements do not cause the loop to stop, because they belong to the switch
.
A caveat on the use of goto
- many programmers consider it poor style, as it can lead to code that is difficult to follow. There is quite a bit of further discussion on this question. In C++, typically throw
is more appropriate for situations where goto
might be used.
However, there are situations in pure C where goto
can be very useful. This answer provides an excellent overview of why goto
is historically considered poor style, and even provides some examples of where it might be appropriate to use goto
.
Of course, a good rule for beginners might be "pretend goto
doesn't exist". Especially in C++.