# The use of function pointer Arrays

Source: Internet
Author: User

Problem prototype:

Switch (nstreamtype)
{
Case 0:
Function1 (); // or function1 (INT)
Break;
Case 1:
......
Case 255:
Function255 (); // or function1 (INT)
Break;
}

The code written in this way is quite long and uncomfortable ..

Think of array of function pointers to improve.

The function name is actually a pointer pointing to the function's entry address, but it is different from common pointers such as int * and double *. Let's look at the following example to understand the concept of the function pointer:
Int funtion (int x, int y );
Void main (void)
{
INT (* Fun) (int x, int y );
Int A = 10, B = 20;
Function (A, B );
Fun = function;
(* Fun) (A, B );
......
}
Statement 1 defines a function. The input value is two integer values, and the return value is also an integer value. (The input parameter and return value can be of any other data type ); statement 3 defines a function pointer. Unlike int * or double *, the function pointer must specify the input parameter at the same time, indicating that this is a function pointer, * Fun must also be enclosed in a pair of parentheses. Statement 6 assigns a function pointer to funtion, provided that * the input parameters and return values of fun and function must be consistent. Statement 5 calls the function () directly, and Statement 7 calls the function pointer. The two are equivalent.

First, define 256 processing functions (and their implementations ).

Int funtion0 (INT );
........
Int funtion255 (INT );

Define the function pointer array and assign values to the array.
INT (* Fun [256]) (INT );

Fun [0] = function0;
.......
Fun [255] = function ();

When calling:

For (int I (0); I <4; ++ I)
{
Cout <"function return value" <(* Fun [I]) (I) <Endl; // call without parameters, write it like this (* Fun [I]) () or * Fun [I]

}

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.