繁体   English   中英

输出这个简单的C程序

[英]Output of this simple C program

我是C ++的中级程序员。 我遇到了这个代码,从1-1000打印数字没有循环,甚至没有递归。 我真的不知道这是如何工作的。 可以解释一下这段代码吗?

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

void function(int j)
{
    static void (*const ft[2])(int) = { function, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
 function(1);
}

只是简单的递归:

static void (*const ft[2])(int) = { function, exit };

首先创建一个函数指针数组,使用fpointers来functionexit ,两者都采用int

然后ft[j/1000](j + 1); 调用元素[j/1000]处的函数,只要j小于[j/1000]就调为0 ,因此function ,否则调用exit

这显然是递归的,它包含一个2元素的函数指针数组,并调用自身( ft[0]function )或exit()退出程序。

这一行:

ft[j/1000](j + 1);

只要j/1000计算结果为0就是递归调用。 它可以改写为:

if(j < 1000)
  function(j + 1);
else
  exit(j + 1);

在函数function内部,声明了一个指向函数本身的指针作为数组的元素

static void (*const ft[2])(int) = { function, exit };
                                    ^^^^^^^^

所以在函数里面这些调用

f( j + 1 );

ft[0]( j + 1 );

是等价的。

表达方式

j / 1000

由于整数运算直到j等于1000因此总是等于0。

因此,函数递归地调用自身1000次。 j等于1000 ,调用函数exit,因为ft[1]是指向exit指针。

该程序可以编写得更简单明了。 例如

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

void function(int j)
{
    printf("%d\n", j);
    if ( j / 1000 == 0 ) f( j + 1 );
}

int main(int argc, char *argv[])
{
    function( 1 );
}

唯一的区别是在原始程序中有一个名为exit的参数1001而该程序成功退出参数0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM