1

Here is a simple code

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void (*func[2])(int);
void main(int n=1)
{
    int i;
    cout<<endl<<n;
    func[0]=&exit;
    func[1]=&main;
    i=++n<=10;
    (func[i])(n);
}

Here I am satisfied with the output (i.e. 1 to 10 in different lines). The only thing which confused me was that why the global pointer is of the type void (*ptr[2])(int). If possible, please explain in simple words that why this pointer was taken so specifically

3
  • 2
    Reading about the clockwise/spiral rule might help you decode it. Commented Jan 31, 2014 at 15:33
  • Also, you should know that technically your program have undefined behavior. The C++ specification says that main must be defined to return an int, and take either no arguments or two arguments (an int and an array of char pointers). Commented Jan 31, 2014 at 15:36
  • @JoachimPileborg : this is a simple code for some riddle so it does not conform to standard c++ programming rules. I got my answer in first comment. Thanks alot eveyone for your time and knowledge Commented Jan 31, 2014 at 15:47

1 Answer 1

3

It's not a pointer, it's an array of two pointers.

This is a function:

void func(int);

This is a pointer to a function:

void (*func)(int);

and this is an array of two pointers to functions:

void (*func[2])(int);

So func[i] points to exit if i is zero (i.e. if n is greater than 10), and points to main otherwise, where i is 1.

Note that you're not allowed to call main recursively like this, nor to give main any signature other than int main() or int main(int, char**). (At least, that's the case in modern C++; these rules presumably don't apply to the prehistoric dialect your compiler accepts).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.