[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/100663/edit).
Closed 7 years ago.
[Improve this question](/posts/100663/edit) 
Let's take a look on a typical loop, which usually performs 8 iterations:
```
for (int x=0; x<8; ++x);
```
You have to make it infinite!
---
It's a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") for all languages that support such form of `for` loop. So solution with highest score (upvotes minus downvotes) wins.
If your language has the other form of `for` loop, but you are sure, you can make something cool with it, feel free to post the answer and mark it as noncompeting. I reserve the right to enlarge scope of available constructions and languages, but it will never be shrinked, so don't be afraid of dropping previously correct solutions.
---
# What is solution?
Solution consists of *two programs.*
The first program is a *clean* program. It's the typical program in your language with the `for` loop making 8 iterations. It should be the normal program, any developer could write. No any special hacks for preparation purposes. For example:
```
int main() 
{
  for (int x=0; x<8; ++x);
  return 0;
}
```
The second program is *augmented.* This program should contain all the code from clean program and some additional code. There are limited number of *extension points,* see complete rules section for details. An augmented program for the clean one above can be
```
inline bool operator < (const int &a, const int &b)
{
  return true;
}
int main() 
{
  for (int x=0; x<8; ++x);
  return 0;
}
```
That's just an example (noncompilable in C++) to show an idea. The real correct augmented program have to be compilable, working and having infinite loop.
# Complete rules
### Both programs:
* Any language with support of such `for` loops is ok.
* The loop body has to be empty. More precisely, you can place some output or other code into the loop, but loop behavior should be the same in case of empty loop.
### Clean program:
* Loop uses integer or numeric counter and performs 8 iterations:
```
for (int          x=0; x<8; ++x);   // C, C++, C#
for (var          x=0; x<8; ++x);   // C#, Javascript
for (auto         x=0; x<8; ++x);   // C, C++
for (auto signed  x=0; x<8; ++x);   // C, C++
for (register int x=0; x<8; ++x);   // C, C++
```
* User-defined types are disallowed.
* Using of property (except of global variable) instead of loop variable is disallowed.
* Declaration of variable can be inside or outside of the loop. Following code is ok:
```
int x;
for(x=0; x<8; ++x);
```
* Either prefix or postfix increment can be used.
* Loop limit `8` should be written as a constant literal without saving to named constant or variable. It's made to prevent solutions based on declaring variable or constant equal to 8, and then reassigning, overriding or shadowing it by the other value:
```
const double n = 8;
int main()
{
  const double n = 9007199254740992;
  for (double x=0; x<n; ++x);
  return 0;
}
```
### Augmented program:
* Must contain all the code from the clean one.
* Should extend clean program in limited number of extension points.
* Must execute *same* `for` loop as an infinite loop itself.  
Placing of the loop into another infinite construction is not ok.
* Runtime or compile-time patching of the code is allowed as long as textual representation of it is unchanged.
* Placing the construction into a string and passing to `eval` is disallowed.
### Extension points:
* Anywhere outside of the fragment with clean code, including other files or other assemblies.
* `for` statement (as single piece - `for` construction and its body) must be kept unchanged.
* Variable declaration must be kept the same.
* Any place between simple statements can be used as extension point.
* If and only if variable was declared outside of the loop and without immediate assignment of the value, such assignment can be added.
```
/* extension point here */
int main()
/* extension point here */
{
  /* extension point here */
  int x /* extension point for assignment here */;
  /* extension point here */
  for (x=0; x<8; ++x);
  /* extension point here */
  return 0;
  /* extension point here */
}
/* extension point here */
```
```
int main() 
{
  /* BEGIN: No changes allowed */ int x = 0; /* END */
  /* extension point here */
  /* BEGIN: No changes allowed */ for (x=0; x<8; ++x); /* END */
  return 0;
}
```
PS: If possible, please provide a link to online IDE.
  
[Answer]
# Python3
### Clean Program:
This is just a standard countdown while loop.
```
n = 8
while n != 0:
  n -= 1
print("done")
```
### Augmented Program:
```
import ctypes
ctypes.cast(id(8), ctypes.POINTER(ctypes.c_int))[6] = 9
n = 8
while n != 0:
  n -= 1
print("done")
```
It uses the int cache to redefine `8` as `9` which effectively makes the `n -= 1` a no-op, since `9-1 = 8` which just sets `n` back to `9` again, causing the infinite loop.
You can see the int cache in action online [here](http://repl.it/E4fx/0) (though obviously without the infinite loop cuz its online).
[Answer]
# Python 3
**Clean Program:**
The standard way to do something 8 times in python is:
```
for i in range(8): 
    # Do something
    pass
```
**Augmented Program:**
However, if we override the range generator function to infinitely yield 1, it becomes an infinite loop...
```
def range(x):
    while 1: yield 1
for i in range(8):
    # Infinite loop
    pass
```
We can take this further and create a generator function which, rather than infinitely yielding 1, counts up forever:
```
def range(x):
    i = 0
    while 1: yield i; i+=1
for i in range(8):
    # Counting from 0 to infinity
    pass
```
[**Test on repl.it**](https://repl.it/E4gu)
[Answer]
# Perl
**Clean**
```
for($i=0; $i<8; $i++) { }
```
**Augmented**
```
*i=*|;
for($i=0; $i<8; $i++) { }
```
[Ideone](http://ideone.com/VrplTE).
[Answer]
# ES5+ (Javascript)
*EDIT*: Removed explicit variable declaration, as otherwise it was hoisted and a non-configurable *window.x* property was created (unless run line by line in the REPL console).
Explanation:
Makes advantage of the fact that any globally scoped variable is also a property of the *window* object, and redefines "window.x" property to have a constant value of 1.
**Clean**
```
for(x=0; x<8; x+=1) console.log(x);
```
**Augmented**
```
Object.defineProperty(window,'x',{value:1});
for(x=0; x<8; x+=1) console.log(x);
```
*NOTE*: To make this work in Node.js, just replace *"window"* with *"global"* (tested in Node.js 6.8.0)
[Answer]
## C
**Clean program**
```
int main() 
{
  for (int x=0; x<8; ++x);
  return 0;
}
```
**Augmented program**
```
#define for(ever) while(1)
int main() 
{
  for (int x=0; x<8; ++x);
  return 0;
}
```
[Answer]
# Java
**Clean program:**
```
public class Main {
    public static void main(String[] args) throws Exception {
        for (Integer i = 0; i < 8; i++);
    }
}
```
**Augmented program:**
```
import java.lang.reflect.Field;
public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] intcache = (Integer[]) c.get(cache);
        intcache[129] = intcache[128];
        for (Integer i = 0; i < 8; i++);
    }
}
```
Sets the Integer in the Integer cache that should contain 1 to 0, effectively making `i++` do nothing (it sets `i` to the cached Integer that should contain 1, but since that Integer actually contains 0, nothing changes).
[Answer]
# C++
```
int main() 
{
#define int bool
  for (int x=0; x<8; ++x);
  return 0;
}
```
`bool` can only be 0 or 1. Inspired by primo's [Perl answer](https://codegolf.stackexchange.com/a/101094/53667).
[Answer]
## Python 3 (3.5.0)
**Clean Program:**
```
for i in range(8):
    print(i)
```
**Augmented**
```
import sys
from ctypes import *
code = sys._getframe().f_code.co_code
cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-4] = 113
cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-3] = 160
for i in range(8):
    print(i)
```
This solution is unlike the others written in Python in that it actually changes the source code on the fly. All the stuff in the for loop can be changed to whatever code is wanted.
The code changes the second to last opcode to be `113` or more readably - `JUMP_ABSOLUTE`. It changes the operand to `160` - the instruction where the for loop begins, in effect creating a GOTO statement at the end of the program.
The augmented program prints the numbers `0..7` infinitely many times without stack-overflowing or similar.
[Answer]
# PHP
I think this is following the extension point rules; I'm not totally clear on point 4. It's very similar to @primo's perl answer so I think it counts.
**Clean**
```
for(;$i<8;$i++);
```
**Augmented**
```
$i='a';
for(;$i<8;$i++);
```
PHP lets you increment certain strings, like so: 
```
'a' -> 'b'
'b' -> 'c'
'z' -> 'aa'
'aa' -> 'ab'
'aab' -> 'aac'
etc
```
All of these strings evaluate to 0, so this will loop practically forever (barring somehow running out of memory).
[Answer]
# Perl
## Clean code
```
for ($x = 0; $x < 8; $x++) {}
```
## Augmented code
```
sub TIESCALAR {bless []}
sub FETCH {}
sub STORE {}
tie $x, "";
for ($x = 0; $x < 8; $x++) {}
```
Most Perl variables are just variables. However, the language also has a `tie` feature, which allows you to effectively give variables getters and setters. In this program, I make the main package (whose name is the null string) into the equivalent of a class from an object-oriented language, whilst also having it be a program. That allows me to tie the `for` loop counter to the program itself. Implementing `TIESCALAR` allows `tie` to succeed; the return value of `TIESCALAR` is meant to be a reference to any internal state we need to keep around associated with the variable, but because we don't need any, we return an empty array reference as a placeholder. We then give the simplest possible implementations of the getter and setter; neither of them do anything, so attempts to assign to `$x` have no effect, and attempts to read it always return `undef`, which is numerically less than 8.
[Answer]
# WinDbg
### Clean
```
.for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { }
```
### Augmented
```
aS < |;                                            * Create alias of < as |
.block {                                           * Explicit block so aliases are expanded
    .for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { } * Condition is now @$t0 | 8, always true
}
```
This approach creates an alias for `<` as `|`, so when `<` is encountered in the code the alias is expanded to `|` and bitwise-or is done instead of less-than. In WinDbg all non-zero values are truthy so `anything | 8` is always true.
Note: The `.block` is not actually needed if the `aS` and `.for` are actually entered as two different lines as shown here, it's only required when the `aS` and `.for` are on the same line.
[Answer]
# Mathematica
## Clean
```
For[x = 0, x < 8, ++x,]
```
## Augmented
```
x /: (x = 0) := x = -Infinity;
For[x = 0, x < 8, ++x,]
```
[Answer]
## Common Lisp
### Clean code
```
(dotimes(i 8))
```
### Augmented
```
(shadowing-import(defmacro :dotimes(&rest args)'(loop)))
(dotimes(i 8))
```
A macro named `keyword:dotimes`, a.k.a. `:dotimes` (see [11.1.2.3 The KEYWORD Package](http://www.lispworks.com/documentation/HyperSpec/Body/11_abc.htm)) is defined which expands as an infinite loop. The [`defmacro`](http://clhs.lisp.se/Body/m_defmac.htm) macro returns the name of the macro being defined, which can be fed to [`shadowing-import`](http://clhs.lisp.se/Body/f_shdw_i.htm). Thus, this new `dotimes` symbols shadows the standard one (which should not be redefined or lexically bound to another macro in portable programs).
### Augmented (2)
```
(set-macro-character #\8 (lambda (&rest args) '(loop)))
(dotimes(i 8))
```
When we read character 8, we replace it by `(loop)`. That means that the above reads as `(dotimes (i (loop)))` and so the code never terminates computating the upper-bound. This impacts all occurrences of 8, not only the one in the loop. 
**In other words, 8 really stands for infinity.**
If you are curious, when the readtable is modified like above, then character 8 becomes "terminating", and detaches itself from other numbers/symbols currently being read:
```
(list 6789)
```
... reads as:
```
(list 67 (loop) 9)
```
You can run tests on Ideone: <https://ideone.com/sR3AiU>.
[Answer]
# Ruby
## Clean
This sort of for loop is not much used in Ruby, but a typical tutorial will tell you that this is the way to go about it:
```
for x in 1..8
  # Some code here
end
```
# Augmented
The for loop just calls `(1..8).each` with the given block of code, so we change that method:
```
class Range
  def each
    i = first
    loop { yield i; i+= 1 }
  end
end
for x in 1..8
  # Some code here
end
```
[Answer]
# Haskell
## Clean version:
```
import Control.Monad (forM_)
main = forM_ [0..8] $ \i -> print i
```
Augmented version:
```
import Control.Monad (forM_)
data T = C
instance Num T where
    fromInteger _ = C
instance Enum T where
    enumFromTo _ _ = repeat C
instance Show T where
    show _ = "0"
default (T)
main = forM_ [0..8] $ \i -> print i
```
It's quite basic, really: we just define our own type `T` such that its `enumFromTo` instance is an infinite sequence, then use type defaulting so that the un-type-annotated values `0` and `8` are taken as type `T`.
[Answer]
# ///
*There are no explicit `for` loops in ///, but can be simulated (it's turing complete after all).*
## Clean:
```
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8
```
## Augmented:
```
/0/0/
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8
```
What's going on?
While the former program counts down from 8 to 0, the latter one's `/0/0/` rule will replace `0` by `0` until eternity.
[Answer]
# Javascript ES6
OK, here's a version that works using the ES6 for...of loop construct. I'll even give you a clean array so that we're sure there's no funny business:
### Clean
```
for(a of [0,1,2,3,4,5,6,7]);
```
Of course, that doesn't stop someone from messing with the Array prototype...
### Augmented
```
Array.prototype[Symbol.iterator]=function(){return {next: function(){return {done: false}}}}
for(a of [0,1,2,3,4,5,6,7]);
```
This works by over-writing the default iterator so that it never terminates, therefore locking everything into an infinite loop. The code doesn't even have a chance to run the stuff inside the loop.
[Answer]
# C++
Uses 2 extension points:
```
struct True {
  True(int x){}
  bool operator<(const int&){
    return true;
  }
  void operator++(){}
};
int main() 
{
#define int True
  for (int x=0; x<8; ++x);
  return 0;
}
```
Clean program is same as in the description.
[Answer]
# Brainfuck
I print a '0' each iteration, just to make it easy to count iterations. But any code could be inserted there without changing how the loop works.
## Clean
```
>> ++++++ [-<++++++++>] <<                   b = '0' (value to be printed each iteration)
>> ++++++++ [-<< ++++++++ ++++++++ >>] <<    for (a = a plus 128;
[                                              a;
++++++++ ++++++++                              a = a plus 16 (mod 256)) {
>.<                                              loop body (print b)
]                                            }
```
[Try it online](http://brainfuck.tryitonline.net/#code=Pj4gKysrKysrIFstPCsrKysrKysrPl0gPDwgICAgICAgICAgICAgICAgICAgYiA9ICcwJyAodmFsdWUgdG8gYmUgcHJpbnRlZCBlYWNoIGl0ZXJhdGlvbikKCj4-ICsrKysrKysrIFstPDwgKysrKysrKysgKysrKysrKysgPj5dIDw8ICAgIGZvciAoYSA9IDEyODsKWyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBhOworKysrKysrKyArKysrKysrKyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGEgPSBhIHBsdXMgMTYgKG1vZCAyNTYpKSB7Cj4uPCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBsb29wIGJvZHkgKHByaW50cyBiKQpdICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9Cg&input=&args=)
The augmented version relies on the common Brainfuck implementation with 8 bit cells. On these implementations, "increment" is actually "increment (mod 256)". Thus to find a loop that will iterate exactly 8 times in the clean version and endlessly in the augmented version, we can simply find a solution to the following system of inequalities.
* a + b\*8 (mod 256) == 0 (for clean version)
* c + a + b\*n (mod 256) > 0 for all n (for augmented version)
* a > 0
In this case, we let a = 128, b = 16, and c = 1. Obviously 128 + 16 \* 8 = 256 (and 256 (mod 256) = 0) and 128 > 0, and since b is even, c + a + b \* n is odd for any odd a + c, and thus will never be an even multiple of 256 in such cases. We select c = 1 for simplicity's sake. Thus the only change we need is a single `+` at the beginning of the program.
## Augmented
```
+                                            increment a (only change)
>> ++++++ [-<++++++++>] <<                   b = '0' (value to be printed each iteration)
>> ++++++++ [-<< ++++++++ ++++++++ >>] <<    for (a = a plus 128;
[                                              a;
++++++++ ++++++++                              a = a plus 16 (mod 256)) {
>.<                                              loop body (print b)
]                                            }
```
[Try it online](http://brainfuck.tryitonline.net/#code=Kwo-PiArKysrKysgWy08KysrKysrKys-XSA8PCAgICAgICAgICAgICAgICAgICBiID0gJzAnICh2YWx1ZSB0byBiZSBwcmludGVkIGVhY2ggaXRlcmF0aW9uKQoKPj4gKysrKysrKysgWy08PCArKysrKysrKyArKysrKysrKyA-Pl0gPDwgICAgZm9yIChhID0gMTI4OwpbICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGE7CisrKysrKysrICsrKysrKysrICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYSA9IGEgcGx1cyAxNiAobW9kIDI1NikpIHsKPi48ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxvb3AgYm9keSAocHJpbnRzIGIpCl0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0K&input=&args=)
I leave it to the OP to determine if this entry is competing. Brainfuck doesn't have an explicit for loop, but the loop form I used is as close as you're likely to get. `++++++++` is also as close to a literal `8` as you can get; I've included quite a few of those.
The clean version almost certainly constitutes a typical program written in this language, as even the [shortest known Brainfuck Hello World](https://codegolf.stackexchange.com/a/68494/44809) depends on a modular recurrence relation to work.
[Answer]
# Haskell
## Clean
```
import Control.Monad (forM_)
main = forM_ [0..8] $ \i -> print i
```
## Augmented
```
import Control.Monad (forM_)
import Prelude hiding (($))
import Control.Monad (when)
f $ x = f (\i -> x i >> when (i == 8) (f $ x))
main = forM_ [0..8] $ \i -> print i
```
Replaces the usual function application operator `$` with one that repeats the loop again every time it finishes. Running the clean version prints 0 to 8 and then stops; the augmented version prints 0 to 8 and then 0 to 8 again, and so on.
I cheat a little, in that `forM_ [0..8] $ \i -> print i` isn't necessarily the "cleanest" way to write that loop in Haskell; many Haskellers would eta-reduce the loop body to get `forM_ [0..8] print` and then there's no `$` to override. In my defense I copied the clean code from [Cactus' answer](https://codegolf.stackexchange.com/a/101432/36334), who didn't need that property, so at least one Haskell programmer actually wrote that code with no motivation to unnecessarily add the `$`!
[Answer]
# C++
```
int main() 
{
  int y;
#define int
#define x (y=7)
  for (int x=0; x<8; ++x);
  return 0;
}
```
Lets `x` evaluate to 7. Does not work in C because it requires an lvalue at assignement and increment.
[Answer]
# Nim
The idiomatic version, using `countup`:
### Clean
```
for i in countup(1, 8):
  # counting from 1 to 8, inclusive
  discard
```
### Augmented
```
iterator countup(a: int, b: int): int =
  while true:
    yield 8
for i in countup(1, 8):
  # counting 8s forever
  discard
```
Simple, and very similar to [the Python answer which redefines `range`](https://codegolf.stackexchange.com/a/100671/56755). We redefine `countup`, the idiomatic Nim way of iterating from one int (inclusive) to another, to give 8s infinitely.
The more interesting version, using the range operator `..`:
### Clean
```
for i in 1..8:
  # counting from 1 to 8, inclusive
  discard
```
### Augmented
```
iterator `..`(a: int, b: int): int =
  while true:
    yield 8
for i in 1..8:
  # counting 8s forever
  discard
```
Very similar to the previous solution, except we redefine the range operator `..`, which normally would give an array `[1, 2, 3, 4, 5, 6, 7, 8]`, to the iterator from before.
[Answer]
# GolfScript
## Clean
```
0{.8<}{)}while;
```
## Augmented
```
{.)}:8;
0{.8<}{)}while;
```
It assigns the function returning n+1 to the variable 8
[Answer]
# tcl
Normal:
```
for {set i 0} {$i<8} {incr i} {}
```
Augmented:
```
proc incr x {}
for {set i 0} {$i<8} {incr i} {}
```
The idea is to redefine the `incr` command that is used to increment the variable `i`, to actually not increment!
Can be tested on: <http://rextester.com/live/QSKZPQ49822>
[Answer]
# x86\_64 Assembly
Clean program:
```
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall
```
The sort of loop any Assembly programmer would use, followed by an exit syscall so as not to enable adding a `jmp loop_start` instruction afterwards.
Augmented program:
```
global start
section .text
start:
mov rcx, -1
jmp loop_start
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall
```
Also, sorry if it's bad that the clean program doesn't have an entrypoint or a `section .text`
[Answer]
# JavaScript
## Clean:
```
for (var i = 0; !(i > Math.PI * 2.5); i++);
```
## Augmented:
```
window.Math = {PI: NaN};
for (var i = 0; !(i > Math.PI * 2.5); i++);
```
[Answer]
# C++
## Clean Program
A nice, normal loop, iterating from numbers 0 to 7.
```
#include <iostream>
int main() {
  for (short i = 0; i < 8; i++) {
    // Print `i` with a newline.
    std::cout << i << std::endl;
  }    
}
```
## Augmented Program
The preprocessor of C++ is quite a dangerous feature...
```
#include <iostream>
#define short bool
int main() {
  for (short i = 0; i < 8; i++) {
    // Print `i` with a newline.
    std::cout << i << std::endl;
  }    
}
```
The only line we had to add was `#define short bool`. This makes `i` a boolean instead of a short integer, and so the increment operator (`i++`) does nothing after `i` reaches 1. The output then looks like this:
```
0
1
1
1
1
1
...
```
]