Gagan93
Gagan93

Reputation: 1876

Calling function via pointer

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

Upvotes: 1

Views: 60

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254631

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).

Upvotes: 3

Related Questions