I’m practicing C++ through Visual C++ Express and tutorials on Youtube. I made a calculator by following a cool video, but I didn’t want the program to end right after you do one equation, so I searched for what to do and tried while(true).
The problem is, instead of a number, when the program prompted me to type in a number, I typed in “blah”, hit enter, and the program started to just go crazy so I exited real quick.
Without the while(true), if I type in “blah”, then the program instantly goes to the “press any button to exit…” phrase. So what I’m wondering is, how dangerous is while(true)?
Also, I’m really sorry if this question is inappropriate-_-
while(true)can obviously create an “infinite” loop, which just means there’s nothing internal to the process capable of causing the loop to terminate. It’s still possible that the Operating System may decide (e.g. after a CPU usage quota is exhausted) or be asked (e.g.kill -HUP processidon UNIX/Linux) to terminate the process.It’s worth considering the difference between infinite loops containing:
x += array[random(array.size())];)The former case may actually be deliberately used in some cases, such as a server process that doesn’t need to do any orderly shutdown and can therefore let the OS shut it down without running any post-loop code, but the second case is usually a programming error: you tend to only have such a
while(true)when there’s some way for an exit condition or error occuring during processing controlled by the loop to interrupt the loop. For example, there may be anif (condition) break;, or something that will throw an exception when there’s an error. This may not be obvious – if could for example be an exception from some function that’s invoked – even from having set the Standard iostream’s functions to throw on conversion failure or EOF – rather than a visiblethrowstatement in the source code within the loop.It’s worth noting that many other things can create infinite loops too – for example
while (a < b)could go forever if there’s no conditions under whichacould become>= b. So, it’s a general aspect of programming that you have to consider how your loops exit, and not some problem with the safety of the language. For inputs, it’s normal to do something like: