Saturday, August 18, 2007

How to Avoid Complex Declarations

How to Avoid Complex Declarations
It is very difficult to track and understand the complex declaration of function pointer.
And also not encouraged in standard programming. Because the readability of the code may suffer.
So, what is the panacea ?Simple , just make it as simple a possible .
Use typedefs to reduce the complexity.

Break down a complex declaration into several simpler declarations.
We will take an example .

Every this is easy if there is a simple example …. Am I correct ?

First declare the typedef for the function pointer:

typedef int (*MY_FUNC_PTR)(int);

From now onwards, MY_FUNC_PTR is a function pointer , to a function which takes an integer and returns an integer.

Now, let us define the type, of the pointer to the function pointer array: MY_FUNC_PTR

typedef MY_FUNC_PTR (*PTR_TO_FPTR_ARRAY)[5];

Declaring the FuncRetArrayPtr function is much simpler now.

PTR_TO_FPTR_ARRAY FuncRetArrayPtr ();

Here is the re-written program:

#include
using namespace std;

typedef int (*MY_FUNC_PTR)(int);

typedef MY_FUNC_PTR (*PTR_TO_FPTR_ARRAY)[5];

int Func1(int x)
{
return x+x;
}

int Func2(int y)
{
return y+y;
}

MY_FUNC_PTR FuncPtrArray[5];

PTR_TO_FPTR_ARRAY FuncRetArrayPtr ()
{
FuncPtrArray[0] = Func1;
FuncPtrArray[1] = Func2;
return &FuncPtrArray;
}

int main()
{
cout << "Calling one ..." << FuncRetArrayPtr()[0][0](10) << endl;

cout << "Calling two ..." << FuncRetArrayPtr()[0][1](10) << endl;

return 0;
}

I have tried to make it as simple as posible. I am planing to write some more pragrams on function pointer. Some more example, and If somebody have some better idea , then please mail me , we can have a discussion . I am aslo planning to write some thing on dynamic casting , virtual mechanism, table, friends function , easy way of link list manupulation.....
cheer,
Sahu
hara.sahu@gmail.com

No comments: