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

用C或c++怎么做呢?


当前回答

如果你的C编译器支持block,那么你可以这样写:

#include <stdio.h>

void ten(void (^b)(void)) { b();b();b();b();b();b();b();b();b();b(); }

int main() {
    __block int i = 0;
    ten(^{
        ten(^{
            ten(^{
                printf("%d\n", ++i);
            });
        });
    });
    return 0;
}

其他回答

以下是我知道的三个解决方案。不过,第二种说法可能存在争议。

// compile time recursion
template<int N> void f1()
{ 
    f1<N-1>(); 
    cout << N << '\n'; 
}

template<> void f1<1>() 
{ 
    cout << 1 << '\n'; 
}

// short circuiting (not a conditional statement)
void f2(int N)
{ 
    N && (f2(N-1), cout << N << '\n');
}

// constructors!
struct A {
    A() {
        static int N = 1;
        cout << N++ << '\n';
    }
};

int main()
{
    f1<1000>();
    f2(1000);
    delete[] new A[1000]; // (3)
    A data[1000]; // (4) added by Martin York
}

[编辑:(1)和(4)只能用于编译时常数,(2)和(3)也可以用于运行时表达式-结束编辑。]]

下面是一个使用setjmp/longjmp的版本,因为必须有人这样做:

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

void print(int i) {
    printf("%d\n", i);
}
typedef void (*func_t)(int);

int main() {
    jmp_buf buf;
    func_t f[] = {print, exit};
    int i = setjmp(buf)+1;
    f[i/1001](i);
    longjmp(buf, i);
    return 0;
}
template <int To, int From = 1>
struct printer {
    static void print() {
        cout << From << endl; 
        printer<To, From + 1>::print();
    }
};    

template <int Done>
struct printer<Done, Done> {
     static void print() {
          cout << Done << endl;
     }
};

int main() 
{
     printer<1000>::print();
}

我通读了所有这些答案,我的答案与其他答案不同。它是标准C语言,使用整数除法从数组中选择函数指针。此外,它在没有警告的情况下正确编译和执行,甚至在没有警告的情况下传递“夹板”。

当然,我也受到了很多其他答案的启发。即便如此,我的更好。

#include <stdio.h>
#include <stdlib.h>

static int x(/*@unused@*/ const char * format, ...) { exit(0); }

static void p(int v, int e) {
    static int (*a[])(const char *, ...) = { printf, x };
    (void)a[v/(e+1)]("%d\n", v);
    p(v+1, e);
}

int main(void) {
    p(1, 1000);
    return 0;
}
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>

int main()
{
  boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '\n');
  return(0);
}