-6

in c++ what is the bets way to make an infinite loop using the for loop method?

Chris.B
  • 7
  • 1

2 Answers2

2

These are some ways through which you can make infinite loops -

  1.  while(1) {
         ..... statements ....
     }
    
  2.  while(true) {
         .... statements ......
     }
    
  3.  for(;;) {
         .... statements ......
     }
    
  4.  do {
         .......statements.....
     } while(true);
    
πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
  • 2
    Please, 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
  • 220,365
  • 33
  • 331
  • 451