任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。

用C或c++怎么做呢?


当前回答

堆栈溢出:

#include <stdio.h>

static void print_line(int i)
{   
 printf("%d\n", i); 
 print_line(i+1);
}   

int main(int argc, char* argv[])
{   
 //get up near the stack limit
 char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
 print_line(1);
} 

这是一个8MB的堆栈。每次函数调用大约占用32个字节(因此是32 * 1000)。但是当我运行它时,我只得到804(因此是196 * 32;也许C运行时在堆栈中有其他部分,你也必须扣除)。

其他回答

既然对bug没有限制…

int i=1; int main() { int j=i/(i-1001); printf("%d\n", i++); main(); }

或者更好(?),

#include <stdlib.h>
#include <signal.h>

int i=1;
int foo() { int j=i/(i-1001); printf("%d\n", i++); foo(); }

int main()
{
        signal(SIGFPE, exit);
        foo();
}

被接受答案的c++变体:

void print(vector<int> &v, int ind)
{
    v.at(ind);
    std::cout << ++ind << std::endl;
    try
    {
        print(v, ind);
    }
    catch(std::out_of_range &e)
    {
    }
}

int main()
{
    vector<int> v(1000);
    print(v, 0);
}

使用宏压缩:

#include <stdio.h>

#define a printf("%d ",++i);
#define b a a a a a
#define c b b b b b
#define d c c c c c
#define e d d d d

int main ( void ) {
    int i = 0;
    e e
    return 0;
}

或者更好:

#include <stdio.h>

#define a printf("%d ",++i);
#define r(x) x x x x x
#define b r(r(r(a a a a)))

int main ( void ) {
    int i = 0;
    b b
    return 0;
}

c++利用RAII

#include <iostream>
using namespace std;

static int i = 1;
struct a
{
    a(){cout<<i++<<endl;}
    ~a(){cout<<i++<<endl;}
}obj[500];

int main(){return 0;}

C语言开发宏

#include <stdio.h>

#define c1000(x) c5(c5(c5(c4(c2(x))))) 
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x))   //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x

int main(int i){c1000(printf("%d\n",i++);)return 0;}

编辑:还有一个,这个很简单

#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d\n",i++);)))return 0;} 

解析:选C

编辑:此c代码包含<=和?:操作符

#include <stdio.h>

int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}
#include <stdio.h>

int show(int i) {
   printf("%d\n",i);
   return( (i>=1000) || show(i+1));
}


int main(int argc,char **argv) {
   return show(1);
}

||操作符使递归调用短路,以显示i为>= 1000时的情况。