user7220615
user7220615

Reputation:

Output of this simple C program

I'm an intermediate programmer of C++. I came across this code which prints number from 1-1000 without loop, not even recursion. 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);
}

Upvotes: 7

Views: 167

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Inside the function function there is declared a pointer to the function itself as an element of an array

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.

Thus the function recursively calls itself 1000 times. When j is equal to 1000 then the function exit is called because ft[1] is pointer to 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.

Upvotes: 0

Hatted Rooster
Hatted Rooster

Reputation: 36473

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.

Then 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.

Upvotes: 7

unwind
unwind

Reputation: 399793

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.

This line:

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

is a recursive call for as long as j/1000 evaluates to 0. It can be rewritten as:

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

Upvotes: 3

Related Questions