S
Stefan Ram
Alessandro Basili said:I have been looking for a way to print the function name (as I name it
in my source code) via the function pointer.
In the following example code, two example functions,
named »beta« and »zeta« are being defined. »nameof«
returns the name of one of these two functions, when
passed a pointer to one of these two functions. So the
programm prints »beta« and »zeta«.
#include <stdio.h> /* puts */
#define F(r,n,b) r n b
#define FUNCTIONS \
F( void, beta,( void ){} )\
F( void, zeta,( void ){} )\
/**/
FUNCTIONS
#undef F
#define F(r,n,b) n,
void( * const function[] )( void )={ FUNCTIONS };
#undef F
#define F(r,n,b) #n,
char const * const name[] ={ FUNCTIONS };
#undef F
int const top = sizeof name / sizeof 0[ name ];
char const * nameof( void( * const f )( void ))
{ for( int i = 0; i < top; ++i )
if( f == function[ i ])return name[ i ]; }
int main( void )
{ puts( nameof( function[ 0 ]));
puts( nameof( function[ 1 ])); }