简体   繁体   English

输出这个简单的C程序

[英]Output of this simple C program

I'm an intermediate programmer of C++. 我是C ++的中级程序员。 I came across this code which prints number from 1-1000 without loop, not even recursion. 我遇到了这个代码,从1-1000打印数字没有循环,甚至没有递归。 And I've literally no idea how is this working. 我真的不知道这是如何工作的。 Can any please explain this code? 可以解释一下这段代码吗?

#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);
}

Just simple recursion: 只是简单的递归:

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

First a function pointer array is created with fpointers to function and exit , both taking an int . 首先创建一个函数指针数组,使用fpointers来functionexit ,两者都采用int

Then ft[j/1000](j + 1); 然后ft[j/1000](j + 1); calls the function at element [j/1000] which is 0 as long as j is less than 1000, so function is called, otherwise exit is called. 调用元素[j/1000]处的函数,只要j小于[j/1000]就调为0 ,因此function ,否则调用exit

This is obviously recursive, it contains a 2-element array of function pointers and calls either itself ( ft[0] is function ) or exit() to exit the program. 这显然是递归的,它包含一个2元素的函数指针数组,并调用自身( ft[0]function )或exit()退出程序。

This line: 这一行:

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

is a recursive call for as long as j/1000 evaluates to 0 . 只要j/1000计算结果为0就是递归调用。 It can be rewritten as: 它可以改写为:

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

Inside the function function there is declared a pointer to the function itself as an element of an array 在函数function内部,声明了一个指向函数本身的指针作为数组的元素

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

So inside the function these calls 所以在函数里面这些调用

f( j + 1 );

and

ft[0]( j + 1 );

are equivalent. 是等价的。

The expression 表达方式

j / 1000

is always equal to 0 due to the integer arithmetic until j is equal to 1000 . 由于整数运算直到j等于1000因此总是等于0。

Thus the function recursively calls itself 1000 times. 因此,函数递归地调用自身1000次。 When j is equal to 1000 then the function exit is called because ft[1] is pointer to exit . j等于1000 ,调用函数exit,因为ft[1]是指向exit指针。

The program can be written much simpler and clear. 该程序可以编写得更简单明了。 For example 例如

#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 );
}

The only difference is that in the original program there is called exit with argument 1001 while this program successfully exits with argument 0. 唯一的区别是在原始程序中有一个名为exit的参数1001而该程序成功退出参数0。

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

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