阅读763 返回首页    go 阿里云 go 技术社区[云栖]


[原创]另类调用 printf 完成任务的方法

昨天逛csdn/c版,看到如下一道题:

函数原形已经给出:int p(int i, int N);

功能:调用该函数,打印如下格式的输出,例p(1, 7);
1
2
3
4
5
6
7
6
5
4
3
2
1

即每行一个数字。(注意:N只打印一次)

要求:

1. 函数中唯一能够调用的函数就是printf。
2. 不准使用如下的关键字:typedef, enum, do, while, for, switch, case, break, continue, goto, if。
3. 不能使用逗号表达式和?:表达式。
4. 函数中只能有一条语句。

很快有人给出了答案,果不出所料,用的是递归。但貌似不符合题目要求1。难道...
断了递归这条路之后,貌似只有用偶得老本行啦:


int p(int i,int N)
{
    __asm__ __volatile__("movl %%esp,%%ebx;0:cmp $0,%0;jz 1f;pushl %%esi;"
                        "pushl %%edi;call _printf;incl %%esi;decl %0;jmp 0b;"
                        "1:cmp $0,%1;jz 2f;pushl %2;pushl %%edi;call _printf;"
                        "decl %1;decl %2;jmp 1b;2:movl %%ebx,%%esp"
                        ::"m"(N-i+1),"m"(N-i),"m"(N-1),"S"(i),"D"("%d/n"));
}

(编译环境 gcc v3.3.1)

over!

最后更新:2017-04-02 00:06:29

  上一篇:go 如何编写lighttpd插件
  下一篇:go 悼念