Reinvent the For loop
C, 45 chars without goto, if, for, ...
Not the smallest solution, but I find this way of doing it quite interesting in C :)
Doesn't use goto
, if
, for
, or any other kind of control structures.
The function by itself (45 chars):
m(){int (*a[])()={m,exit};i++;(*a[i>999])();}
A compilable, working program:
#include <stdio.h>
#include <stdlib.h>
int i=0;
m(){int (*a[])()={m,exit};i++;printf("%i ",i);(*a[i>999])();}
int main()
{
m();
}
Haskell, 33 chars
This is more like inventing the for loop, because there is no such nonsense in Haskell :P.
mapM_(putStr.(' ':).show)[0..999]
GCC - 106 95 chars
#define FOR(i,l,h)auto F();L(F,l,h);int F(i)
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}
Unlike the other C solutions where you have to declare a callback, this one does it for you automagically:
FOR(i, 1, 10) {
printf("%d\n", i);
}
It works by using GCC's nested function extension. Namely, it forward-declares the nested function F
, passes it to the looping function L
, and then starts the definition of F
, leaving the braces for the user to add.
One beautiful thing about nested functions in GCC is that they support downward funargs, meaning the illusion is nearly complete:
long n = 1;
FOR(i, 1, 10) {
n *= i;
}
printf("%ld\n", n); // 3628800
There is one major caveat: if you use FOR
twice in the same scope, you'll get a conflict (namely, it will compile, but all the FOR
loops will share one loop body). To allow multiple FOR loops in the same scope, we'll need 69 65 more characters:
175 160 chars:
#define FOR(i,l,h)F(i,l,h,__COUNTER__)
#define F(i,l,h,f)auto N(f)();L(N(f),l,h);int N(f)(i)
#define N(n)F##n
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}