in c++ what is the bets way to make an infinite loop using the for loop method?
Asked
Active
Viewed 146 times
-6
-
2The classic method:`for (;;) {}` There are probably some duplicates at SO. – R Sahu Oct 12 '18 at 06:08
-
1`for(;;) {}` should do the trick. – πάντα ῥεῖ Oct 12 '18 at 06:08
-
Possible duplicate of [Endless loop in C/C++](https://stackoverflow.com/questions/20186809/endless-loop-in-c-c) – Adrian W Oct 12 '18 at 06:58
2 Answers
2
These are some ways through which you can make infinite loops -
while(1) { ..... statements .... }
while(true) { .... statements ...... }
for(;;) { .... statements ...... }
do { .......statements..... } while(true);

πάντα ῥεῖ
- 1
- 13
- 116
- 190

Muskan Agarwal
- 31
- 7
-
2Please, consider mentioning that a truely infinte loop would have Undefined Behavior, according to the standard. – Bob__ Oct 12 '18 at 06:20
-
1@Bob__ - it's actually an infinite loop without side effects (or more accurately, such a loop that can't be proven to terminate i.e. be finite) that has undefined behaviour. A fair few experts would have trouble explaining that coherently; beginners even less so. – Peter Oct 12 '18 at 06:52
-
@Peter: And your comment too is showing how hard it is - the problem for the Standard is that statements like "can't be proven" are not implementable. Do compilers need a theorem prover? How good would they need to be? – MSalters Oct 12 '18 at 10:30
-
@MSalters - quite so. I don't claim to be able to fully explain the concern either. The point in my previous comment is that Bob__ had suggested this answer be modified to comment on something that is actually a fairly difficult corner of C++ (as well as being beyond what the question sought). – Peter Oct 12 '18 at 12:45
0
It's surprisingly difficult, although the request is also surprisingly illogical. Empty infinite loops are undefined behaviour in C++.
See Optimizing away a "while(1);" in C++0x
Really though such a thing is unnecessary - simply terminate your program instead. In a sense that is equivalent to having a program that consumes no input and outputs nothing, running forever.

Bathsheba
- 231,907
- 34
- 361
- 483