Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print 1 to 1000 with out using loop [duplicate]

Tags:

c

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

like image 390
Arunprasanth K V Avatar asked Nov 04 '14 09:11

Arunprasanth K V


2 Answers

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.

like image 184
LoPiTaL Avatar answered Nov 19 '22 16:11

LoPiTaL


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.

like image 4
Gopi Avatar answered Nov 19 '22 16:11

Gopi