「Cキーワード分析」のtypedefとcallback
1749 ワード
一、typedef定義関数ポインタタイプ
1.ソースコード
2.c
2.コンパイル運転
gcc -o 2 2.c
./2
二、関数ポインタタイプ
1.int(*func)(int,int)の理解
上の式では、左から右に4つの演算子()、*、()があります.
演算子の優先度()は*より高く、()の結合方向は左から右、*の結合方向は右から左です.
()結合は左から右で、これはポインタ変数funcを定義し、次は後かっこで、関数タイプを定義するポインタfuncであることを示します.
次に、この変数funcは、パラメータが2つのintであり、戻り値がintの関数であるポインタ変数を指す.
2.ソースコード
1.c
2.コンパイルと実行
gcc -o 1 1.c
./1
1.ソースコード
2.c
#include <stdio.h>
typedef int (*HAL_CALL_BACK)(int,int);
int test(int a,int b);
int add(void* func,int a,int b);
int main(){
// printf("TK------>>>test is 0x%lx
",test);
int result = add((void*) test,3,4);
printf("TK------>>>>result is %d
",result);
return 0;
}
int test(int a,int b){
return a + b;
}
int add(void* func,int a,int b){
HAL_CALL_BACK test2 = (HAL_CALL_BACK)func;
int (*test1)(int,int) = (HAL_CALL_BACK)func;
//printf("TK------->>>>>func is 0x%lx
",func);
return test1(a,b);
}
2.コンパイル運転
gcc -o 2 2.c
./2
TK------>>>>result is 7
二、関数ポインタタイプ
1.int(*func)(int,int)の理解
上の式では、左から右に4つの演算子()、*、()があります.
演算子の優先度()は*より高く、()の結合方向は左から右、*の結合方向は右から左です.
()結合は左から右で、これはポインタ変数funcを定義し、次は後かっこで、関数タイプを定義するポインタfuncであることを示します.
次に、この変数funcは、パラメータが2つのintであり、戻り値がintの関数であるポインタ変数を指す.
2.ソースコード
1.c
#include <stdio.h>
//typedef int (*HAL_CALL_BACK)(int,int);
int test(int a,int b);
int add(int func(int,int),int a,int b);
int main(){
// printf("TK------>>>test is 0x%lx
",test);
int result = add(test,3,4);
printf("TK------>>>>result is %d
",result);
return 0;
}
int test(int a,int b){
return a + b;
}
int add(int func(int,int),int a,int b){
int (*test1)(int,int) = func;
//printf("TK------->>>>>func is 0x%lx
",func);
return test1(a,b);
}
2.コンパイルと実行
gcc -o 1 1.c
./1
TK------>>>>result is 7