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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With