20
\$\begingroup\$

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

PS: If possible, please provide a link to online IDE.

\$\endgroup\$
14
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – Qwertiy
    Commented Nov 21, 2016 at 21:19
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Qwertiy
    Commented Nov 21, 2016 at 22:51
  • 4
    \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Commented Nov 21, 2016 at 23:26
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 24, 2016 at 14:08
  • 1
    \$\begingroup\$ 1. Yes, it does. 2. What exactly winning creteria? PS: We can continue on meta. \$\endgroup\$
    – Qwertiy
    Commented Nov 24, 2016 at 14:40

27 Answers 27

31
\$\begingroup\$

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

\$\endgroup\$
7
  • \$\begingroup\$ Could you provide a link to onlinde IDE, please? ideone.com/aI3ZrI - seems not working there. \$\endgroup\$
    – Qwertiy
    Commented Nov 21, 2016 at 22:11
  • \$\begingroup\$ @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 \$\endgroup\$
    – Maltysen
    Commented Nov 21, 2016 at 22:12
  • \$\begingroup\$ 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 \$\endgroup\$
    – Qwertiy
    Commented Nov 21, 2016 at 22:14
  • \$\begingroup\$ @Qwertiy link without the loop: repl.it/E4fx/0 \$\endgroup\$
    – Maltysen
    Commented Nov 21, 2016 at 22:15
  • \$\begingroup\$ That's interesting... \$\endgroup\$
    – Qwertiy
    Commented Nov 21, 2016 at 22:16
22
\$\begingroup\$

Perl

Clean

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

Augmented

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

Ideone.

\$\endgroup\$
1
  • 18
    \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Commented Nov 25, 2016 at 12:45
21
\$\begingroup\$

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

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Hide that in the middle of a huge module... \$\endgroup\$
    – Benjamin
    Commented Dec 16, 2016 at 3:31
10
\$\begingroup\$

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)

\$\endgroup\$
9
  • 1
    \$\begingroup\$ By the way, it's ES5, isn't it? \$\endgroup\$
    – Qwertiy
    Commented Nov 22, 2016 at 9:55
  • \$\begingroup\$ Also it doen't work with var in Crome. But you can remove var from both programs - it'll be ok. \$\endgroup\$
    – Qwertiy
    Commented Nov 22, 2016 at 9:57
  • \$\begingroup\$ @Qwertiy this does work with "var" in Chrome for me (Linux/Version 52.0.2743.82 (64-bit)) \$\endgroup\$
    – zeppelin
    Commented Nov 22, 2016 at 9:58
  • \$\begingroup\$ >By the way, it's ES5, isn't it? True, will correct the title now \$\endgroup\$
    – zeppelin
    Commented Nov 22, 2016 at 9:59
  • 1
    \$\begingroup\$ 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.sstatic.net/lSwbE.png \$\endgroup\$
    – Qwertiy
    Commented Nov 22, 2016 at 10:22
10
\$\begingroup\$

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;
}
\$\endgroup\$
4
  • \$\begingroup\$ Must execute same for loop as an infinite loop itself. Placing of the loop into another infinite construction is not ok. \$\endgroup\$
    – Karl Napf
    Commented Nov 25, 2016 at 13:39
  • 3
    \$\begingroup\$ @KarlNapf The "for" loop is not inside another infinite construction. \$\endgroup\$
    – coredump
    Commented Nov 25, 2016 at 13:41
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – Omar
    Commented Nov 25, 2016 at 16:00
  • \$\begingroup\$ It is the wording "Must execute same for loop" but yes this conflicts with the textual representation. \$\endgroup\$
    – Karl Napf
    Commented Nov 25, 2016 at 18:08
8
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Beat me to it, this solution is identical to my own. \$\endgroup\$
    – Hypino
    Commented Nov 25, 2016 at 16:45
  • 6
    \$\begingroup\$ This isn't really an idiomatic Java for loop, which would probably use the unboxed int rather than the relatively heavyweight Integer. \$\endgroup\$
    – user62131
    Commented Nov 25, 2016 at 17:11
7
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Qwertiy
    Commented Nov 25, 2016 at 15:41
  • 2
    \$\begingroup\$ @Qwertiy "so that's some edge case." PHP in a nutshell :) \$\endgroup\$ Commented Nov 25, 2016 at 16:03
6
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

Mathematica

Clean

For[x = 0, x < 8, ++x,]

Augmented

x /: (x = 0) := x = -Infinity;
For[x = 0, x < 8, ++x,]
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Nice idea to change the default type for Haskell's overloaded numeric literals. \$\endgroup\$
    – nimi
    Commented Nov 29, 2016 at 15:15
3
\$\begingroup\$

///

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.

\$\endgroup\$
1
  • \$\begingroup\$ And I thought that you would actually do something like /0/1//1/2/.../7/8//8/8/8 to count up instead. \$\endgroup\$ Commented Dec 13, 2016 at 12:23
3
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\begingroup\$ "loop behavior should be the same in case of empty loop" \$\endgroup\$
    – Qwertiy
    Commented Nov 29, 2016 at 15:20
  • \$\begingroup\$ Darn, missed that - I'll have to figure something out. \$\endgroup\$ Commented Nov 29, 2016 at 15:23
  • \$\begingroup\$ 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). \$\endgroup\$ Commented Nov 29, 2016 at 15:41
  • \$\begingroup\$ Actually there are some ways. Way with global variable is already posted, bute there are some more, allowing var in the loop. \$\endgroup\$
    – Qwertiy
    Commented Nov 29, 2016 at 18:50
  • \$\begingroup\$ Like I said, as far as I can tell. I saw the global variable way after making that comment and kicked myself. \$\endgroup\$ Commented Nov 29, 2016 at 19:55
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Nice, but can be "optimized" :) There are some interesting builtins in C++ to make another answer. \$\endgroup\$
    – Qwertiy
    Commented Nov 25, 2016 at 13:16
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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 $!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

GolfScript

Clean

0{.8<}{)}while;

Augmented

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

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Won't it stop after integer overflow? \$\endgroup\$
    – Qwertiy
    Commented Feb 6, 2017 at 6:10
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – Morgan H
    Commented Feb 8, 2017 at 16:31
0
\$\begingroup\$

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++);
\$\endgroup\$
2
  • \$\begingroup\$ Doesn't seem to be a typical loop... \$\endgroup\$
    – Qwertiy
    Commented Nov 29, 2016 at 10:32
  • \$\begingroup\$ Yeah, I kinda stretched the term typical... :/ \$\endgroup\$ Commented Nov 29, 2016 at 11:48
0
\$\begingroup\$

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
...
\$\endgroup\$
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.