I encountered the same example a few days before and had spent time to understand it. I am very happy to see someone else who came across the same example if not the same webpage :)
let's analyze the code line by line
First LINE
void main(int j)
I guess if you change the line above into void main(int argc)
you will maybe know that j
will hold exactly the same value of argc
which is 1
as no arguments will be entered while executing the program
In fact the first parameter in main()
function will hold always the number of arguments entered to the program including the name of the program
so if I write
./exeProgram // j contains 1
j
will contain 1
but if you execute with an extra argument it
will hold 2
./exeProgram arg1 // j contains 2
Second LINE
printf("%d\n",j);
this is a simple instruction that print the value of j
so let's move to the third line
the most important
Third LINE
(&main + (&exit - &main)*(j/1000))(j+1);
what the statement here is trying to do is executing the main()
again and
again (in a recursive way) to execute the instruction in a specific number of time
let's see the expression &main + (&exit - &main)*(j/1000)
:
the first term that will be executed will be (&exit - &main)*(j/1000)
here as j
is an integer and so 1000
so the result is always an integer but the problem is that when j
holds a value in 1 ... 99
which is < 1000
the return value of j/1000
will be 0
so for j
between [1..99]:
&main + (&exit - &main)*(j/1000)
becomes &main + (&exit - &main)*(0)
which is
nothing but &main
**
the problem here is that substracting two pointers which don't point to the same array is considered as an undefined behavior !!
**
I will continue the analysis because the idea and the recursive approach is nice and can be used in other working situations !
so for j=1000
now:
&main + (&exit - &main)*(j/1000)
becomes &main + (&exit - &main)*(1)
which is &main+&exit-&main
which is &exit
so let's summarize
if(j>=1 && j<=99)
&main(j) // will be executed when j<=99 and j>=1
else
&exit(j) // will be executed when j=1000
when the program reaches the 1000
value it will execute the function exit()
and stop its execution that's it ! :)
Please note that no need to add the &
before the main
or exit
as the function name refers always to it's address.