# 8 ought to become Infinity [closed]

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 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;
}


• @Oliver, as I know, "highest score (upvotes minus downvotes)" is exactly the defaults for popularity-contest, at least it is written in the tag description: "A popularity contest is a competition where the answer with the highest vote tally (upvotes minus downvotes) wins." But I can add it to the question explicitly. – Qwertiy Nov 21 '16 at 21:19
• @Maltysen, there is a lot of interesting solutions in languages with these construction. There are C and C++ (with absolutely different solutions), C#, Java, Javascript, php, Perl, Groovy. I'm sure there are much more. Anyway, I'm open to enlarge question and that's specified in rules. If you can make something iteresting in other language - post it. If it will have positive reation, rules can be enlarged. – Qwertiy Nov 21 '16 at 22:51
• Doing this as a popularity-contest is a little awkward because there's no description of what criteria voters should choose when voting (making the victory condition subjective). I was working on a code-golf solution on the basis that many people here find golf solutions interesting and thus it might be popular; that seems like it might be a workable victory condition for the challenge. – user62131 Nov 21 '16 at 23:26
• 1. "integer or numeric counter" is a bit too vague. E.g. does it include java.lang.Integer? 2. This would better with a proper winning criterion. – Peter Taylor Nov 24 '16 at 14:08
• 1. Yes, it does. 2. What exactly winning creteria? PS: We can continue on meta. – Qwertiy Nov 24 '16 at 14:40

# 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 (though obviously without the infinite loop cuz its online).

• Could you provide a link to onlinde IDE, please? ideone.com/aI3ZrI - seems not working there. – Qwertiy Nov 21 '16 at 22:11
• @Qwertiy, I tried running it in repl.it, but it just freezes, which is to be expected since it'll be an infinite loop. i know the int cache stuff works there, because that's where I experimented with how to set 8 to 9 – Maltysen Nov 21 '16 at 22:12
• Really works there. Strange that thay haven't time limit like ideone (5 sec). They show Python 3.5.2 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux – Qwertiy Nov 21 '16 at 22:14
• @Qwertiy link without the loop: repl.it/E4fx/0 – Maltysen Nov 21 '16 at 22:15
• That's interesting... – Qwertiy Nov 21 '16 at 22:16

# 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

• Hide that in the middle of a huge module... – Benjamin Dec 16 '16 at 3:31

# Perl

Clean

for($i=0;$i<8; $i++) { }  Augmented *i=*|; for($i=0; $i<8;$i++) { }

• Oh, that's really clever. For anyone who doesn't know Perl: this is aliasing $i to become an alias for a special variable that's only capable of holding booleans, so once it reaches 1 it becomes immune to being incremented. – user62131 Nov 25 '16 at 12:45 # 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) • By the way, it's ES5, isn't it? – Qwertiy Nov 22 '16 at 9:55 • Also it doen't work with var in Crome. But you can remove var from both programs - it'll be ok. – Qwertiy Nov 22 '16 at 9:57 • @Qwertiy this does work with "var" in Chrome for me (Linux/Version 52.0.2743.82 (64-bit)) – zeppelin Nov 22 '16 at 9:58 • >By the way, it's ES5, isn't it? True, will correct the title now – zeppelin Nov 22 '16 at 9:59 • The problem is var hoists, so at the moment of using defineProperty it already exitst. But if you place these 2 lines in different scripts (by the way, it's allowed), it would work, as the property will be created first and the var then will be ignored. Proof: i.stack.imgur.com/lSwbE.png – Qwertiy Nov 22 '16 at 10:22 ## 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; }  • Must execute same for loop as an infinite loop itself. Placing of the loop into another infinite construction is not ok. – Karl Napf Nov 25 '16 at 13:39 • @KarlNapf The "for" loop is not inside another infinite construction. – coredump Nov 25 '16 at 13:41 • @KarlNapf I thought this answer was explicitly allowed by the rule: •Runtime or compile-time patching of the code is allowed as long as textual representation of it is unchanged. – Omar Nov 25 '16 at 16:00 • It is the wording "Must execute same for loop" but yes this conflicts with the textual representation. – Karl Napf Nov 25 '16 at 18:08 # 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). • Beat me to it, this solution is identical to my own. – Hypino Nov 25 '16 at 16:45 • This isn't really an idiomatic Java for loop, which would probably use the unboxed int rather than the relatively heavyweight Integer. – user62131 Nov 25 '16 at 17:11 # 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. ## 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. # 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).

• That's in the spirit of the competition and very interesting. Actually there wasn't said anything about ommiting initial assignmnet, so that's some edge case. Actually it was expected that there is no extension point between assigning 0 and iterations. But I'm not going to disallow it now as I see some interesing edge case ways based on that and it's not easy to overuse. – Qwertiy Nov 25 '16 at 15:41
• @Qwertiy "so that's some edge case." PHP in a nutshell :) – ToXik-yogHurt Nov 25 '16 at 16:03

# Perl

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.

# 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. # Mathematica ## Clean For[x = 0, x < 8, ++x,]  ## Augmented x /: (x = 0) := x = -Infinity; For[x = 0, x < 8, ++x,]  ## 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) is defined which expands as an infinite loop. The defmacro macro returns the name of the macro being defined, which can be fed to shadowing-import. 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. # 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  # 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. • Nice idea to change the default type for Haskell's overloaded numeric literals. – nimi Nov 29 '16 at 15:15 # /// 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. • And I thought that you would actually do something like /0/1//1/2/.../7/8//8/8/8 to count up instead. – Erik the Outgolfer Dec 13 '16 at 12:23 # 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. • "loop behavior should be the same in case of empty loop" – Qwertiy Nov 29 '16 at 15:20 • Darn, missed that - I'll have to figure something out. – Marcus Dirr Nov 29 '16 at 15:23 • As far as I can tell, it isn't possible to do what the challenge with a C-style for loop in Javascript unless you break a rule - either by having something inside it (like my solution) or by pre-massaging the loop declaration in your clean code (like with Cedric Reichenbach's). – Marcus Dirr Nov 29 '16 at 15:41 • Actually there are some ways. Way with global variable is already posted, bute there are some more, allowing var in the loop. – Qwertiy Nov 29 '16 at 18:50 • Like I said, as far as I can tell. I saw the global variable way after making that comment and kicked myself. – Marcus Dirr Nov 29 '16 at 19:55 # 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. • Nice, but can be "optimized" :) There are some interesting builtins in C++ to make another answer. – Qwertiy Nov 25 '16 at 13:16 # 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 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 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 depends on a modular recurrence relation to work. # 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, who didn't need that property, so at least one Haskell programmer actually wrote that code with no motivation to unnecessarily add the $!

# 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.

# Nim

The idiomatic version, using countup:

### Clean

for i in countup(1, 8):
# counting from 1 to 8, inclusive


### Augmented

iterator countup(a: int, b: int): int =
while true:
yield 8

for i in countup(1, 8):
# counting 8s forever


Simple, and very similar to the Python answer which redefines range. 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


### Augmented

iterator ..(a: int, b: int): int =
while true:
yield 8

for i in 1..8:
# counting 8s forever


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.

# GolfScript

## Clean

0{.8<}{)}while;


## Augmented

{.)}:8;
0{.8<}{)}while;


It assigns the function returning n+1 to the variable 8

# 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

# 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

• Won't it stop after integer overflow? – Qwertiy Feb 6 '17 at 6:10
• Oh, uh... maybe. But it will take a long time? I kind of forgot that that could happen, being mostly a high-level-language programmer – goose121 Feb 8 '17 at 16:31

# 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++);

• Doesn't seem to be a typical loop... – Qwertiy Nov 29 '16 at 10:32
• Yeah, I kinda stretched the term typical... :/ – Cedric Reichenbach Nov 29 '16 at 11:48

# 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
...