GeeksforGeeks » C/C++ Programming Questions

Please explain it

(2 posts)

Tags:

  1. nimesh
    guest
    Posted 1 year ago #

    Following code prints 1 to 100 without using loop and without using recursion!!. Could someone please explain how does this code work.

    
    #include <stdio.h>
    
    unsigned counter=1;
    unsigned address=0;
    
    void init(unsigned dummy)
    {
      unsigned *dummyPtr=&dummy;
    
      dummyPtr = dummyPtr - 1;
    
      address=*(unsigned*)dummyPtr;
    }
    
    int printAll(unsigned maxNo)
    {
      unsigned *localPtr=&maxNo;
    
      printf("%u\n", counter);
    
      counter++;
    
      if(counter != maxNo+1)
      {
        if((localPtr = localPtr -1) != 0)
        {
          (*(unsigned*)localPtr=address) !=0;
    
        }
      }
      return 0;
    }
    
    int main(void)
    {
      init(0);
      printAll(100);
      getchar();
      return 0;
    }
    
  2. Venki
    Moderator
    Posted 1 year ago #

    @Nimesh, It is nothing but recursion. The code depends on stack frame construction. See the following comments on code.

    As we know the stack is used to store arguments and return addresses, and what we call it as stack frame. The 'init' function takes one argument named as "dummy".

    The dummy variable is passed on the stack frame (is it guaranteed to be on stack due to 'address of' operator). Before pushing the "dummy" argument the compiler places "return address" where the control to be returned after 'init' is finished. Inside 'init' we are storing this return address in 'address' global variable as unsigned integer (after all address is also an integer).

    Inside "printAll" the local pointer "localPtr" is made to point to the "to be" returned address of "printAll" function. This is again overwritten by the return address of 'init' function which was called before printAll (the statement "*(unsigned*)localPtr = address"). Hence the control goes back to start of "printAll" function. Inside 'printAll' we are using a global variable 'counter' to keep track of number of times we "reset return address". The 'if' conditions are to test the end of count.

    This code is highly non-portable. Depends on compiler.


Reply

You must log in to post.

RSS feed for this topic