I want to make an array of constant pointers to functions. Something like this:
#include <stdio.h>
#include <stdlib.h>
int f( int x);
int g( int x );
const int ( *pf[ ] )( int x ) = { f, g };
int main(void)
{
int i, x = 4, nf = 2;
for( i = 0; i < nf; i++ )
printf( "pf[ %d ]( %d ) = %d \n", i, x, pf[ i ]( x ) );
return EXIT_SUCCESS;
}
int f( int x )
{
return x;
}
int g( int x )
{
return 2*x;
}
It works "fine" when it is compiled without the -Werror flag, but otherwise I get:
Building file: ../src/probando.c
Invoking: GCC C Compiler
gcc -O0 -g3 -pedantic -pedantic-errors -Wall -Wextra -Werror -Wconversion -c -fmessage-length=0 -MMD -MP -MF"src/probando.d" -MT"src/probando.d" -o "src/probando.o" "../src/probando.c"
../src/probando.c:17:14: error: type qualifiers ignored on function return type [-Werror=ignored-qualifiers]
../src/probando.c:17:1: error: initialization from incompatible pointer type
../src/probando.c:17:1: error: (near initialization for ‘pf[0]’)
../src/probando.c:18:1: error: initialization from incompatible pointer type
../src/probando.c:18:1: error: (near initialization for ‘pf[1]’)
cc1: all warnings being treated as errors
make: *** [src/probando.o] Error 1
Thanks in advance.
The
const
is misplaced. As it stands, the functions are supposed to returnconst int
(which makes little sense). What you want is:This way it reads: array of "const pointers to function".