通过运行以下代码,您将知道发生了什么:
#include <stdio.h>
void function_1(char *);
void function_2(char *);
void function_3(char *);
void function_4(char *);
#define func_1 1
#define func_2 2
#define func_3 3
#define func_4 4
void (*functab[])(char *) = { // pay attention to the order
[func_2] function_2,
[func_3] function_3,
[func_1] function_1,
[func_4] function_4
};
int main()
{
int n;
printf("%s","Which of the three functions do you want call (1,2, 3 or 4)?\n");
scanf("%d", &n);
// The following two calling methods have the same result
(*functab[n]) ("print 'Hello, world'"); // call function by way of the function name of function_n
functab[n] ("print 'Hello, world'"); // call function by way of the function pointer which point to function_n
return 0;
}
void function_1( char *s) { printf("function_1 %s\n", s); }
void function_2( char *s) { printf("function_2 %s\n", s); }
void function_3( char *s) { printf("function_3 %s\n", s); }
void function_4( char *s) { printf("function_4 %s\n", s); }
结果:
Which of the three functions do you want call (1,2, 3 or 4)?
1
function_1 print 'Hello, world'
function_1 print 'Hello, world'
Which of the three functions do you want call (1,2, 3 or 4)?
2
function_2 print 'Hello, world'
function_2 print 'Hello, world'
Which of the three functions do you want call (1,2, 3 or 4)?
3
function_3 print 'Hello, world'
function_3 print 'Hello, world'
Which of the three functions do you want call (1,2, 3 or 4)?
4
function_4 print 'Hello, world'
function_4 print 'Hello, world'