9

i see the question on a c++ programming context, i check for a solution and one of my friend give me this code its works perfect but i can't understand it's logic and also how it's works. i asked to him about it but he also don't know how the program is actually works, i think he is also take this solution from somewhere. Anybody can explain the logic behind this i mean in the line (&main + (&exit - &main)*(j/1000))(j+1); ?

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

void main(int j) {
  printf("%d\n", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}

Thanks in advance

Arunprasanth K V
  • 20,733
  • 8
  • 41
  • 71

2 Answers2

28

It works as follows:

Performs the int division j/1000, which will return 0 always while j is smaller than 1000. So the pointer operation is as follows:

&main + 0 = &main, for j < 1000.

Then it calls the resulting function pointed by the pointer operations passing as parameter j+1. While j is less than 1000, it will call main recursively with parameter one more than the step before.

When the value of j reaches 1000, then the integer division j/1000 equals to 1, and the pointer operation results in the following:

&main + &exit - &main = &exit.

It then calls the exit function, which finishes the program execution.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
LoPiTaL
  • 2,495
  • 16
  • 23
  • does the exit function must be written explicitly? or it can be deduced from the main? – antonpuz Nov 04 '14 at 09:37
  • 2
    The exit function is from the C std library, defined in stdlib.h. – LoPiTaL Nov 04 '14 at 09:39
  • It basically "linearly interpolates" the difference from the `MAIN` function to the `EXIT` function, with `integer-division` so that the switch from `A to B` is *instantaneous* once `1001` has been reached - and the integer is increased each time from the *recursive call* of `MAIN`. – EpicPandaForce Nov 04 '14 at 12:37
4

I go with the explanation already given but it would be easier to understand if written as below:

void main(int j) {
   if(j == 1001)
      return;
   else
   {   
      printf("%d\n", j); 
      main(j+1);
   }   
}

The above code does the same as already written code.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • 1
    Realy this is more simple than the above .but logic is different – Arunprasanth K V Nov 04 '14 at 10:52
  • The idea is the same though. The one you have has just been obfuscated, this is the canonical way to do recursion :- though you wouldn't usually use `main` to do it as it technically isn't a valid `main` signature iirc – Baldrickk Nov 04 '14 at 10:56
  • 1
    really this is more simple method rather than above one. thanks for your replay – Arunprasanth K V Nov 04 '14 at 11:36
  • @ArunPrasanth np. The idea behind this is recursion and this would make you understand the code easily instead of the code which you have posted – Gopi Nov 04 '14 at 12:00