Langage C avancé A propos des pointeurs sur fonctions

Transcription

Langage C avancé A propos des pointeurs sur fonctions
Langage C avancé
A propos des pointeurs sur fonctions
Samuel KOKH
Maison de la Simulation - CEA Saclay
[email protected]
MACS 1 (2014-2015) – Institut Galilée
S. KOKH (MdlS)
Langage C avancé
ISPG/MACS 1 2014-2015
1/6
1
2
3
1
2
3
4
5
Pointeurs sur fonctions
Comment écrire un pointeur vers une fonction ?
Soit la fonction déclarée comme suit :
return_type f ( type1 arg1 ,... , typeN argN ){
...
}
pointeur sur la fonction f
return_type (* pf ) ( type1 ,... , typeN ) = NULL ;
pf = & f ;
/* ecriture equivalente */
pf = f ;
S. KOKH (MdlS)
Langage C avancé
ISPG/MACS 1 2014-2015
2/6
1
2
3
4
Utilisation d’un pointeur de fonction (1)
Appel d’une fonction via un pointeur
f ( x1 , x2 ,... , xN );
// appel classique de la fonction
(* pf )( x1 , x2 ,... , xN ); // appel via le pointeur
pf ( x1 , x2 ,... , xN );
// appel via le pointeur :
S. KOKH (MdlS)
Langage C avancé
ISPG/MACS 1 2014-2015
3/6
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
Utilisation d’un pointeur de fonction (2)
double fct ( double x ){
return 3* x +1;
}
int main ( void ){
double (* pF ) ( double ) = NULL ;
double res = 0.0;
pF = & fct ;
res = (* pF )(3.4);
res = pF (12.9);
printf ( " res = % g \ n " , res );
return EXIT_SUCCESS ;
}
S. KOKH (MdlS)
Langage C avancé
ISPG/MACS 1 2014-2015
4/6
1
2
3
4
5
6
7
Utilisation d’un pointeur de fonction
Pointeur de fonction en tant qu’argument d’une autre fonction
Argument d’une fonction
/* declaration de fonction */
void SolvePb ( float (* g ) ( float , float ) , float x0 ){
...
// appel de la fonction pointée par g
(* g )( x0 , x0 *3.14);
...
}
S. KOKH (MdlS)
Langage C avancé
ISPG/MACS 1 2014-2015
5/6
1
2
3
4
5
6
7
8
9
0
1
Utilisation d’un pointeur de fonction
Pointeur de fonction au sein d’une structure
typedef struct A_t {
int data ;
int (* pf1 )( int , int );
int (* pf2 )( int , int );
};
...
// Appel
int a , b ;
A_t A ;
A . pf1 (a , b );
S. KOKH (MdlS)
Langage C avancé
ISPG/MACS 1 2014-2015
6/6