Reputation: 65
I've written a simple C program to learn usage of function pointers:
#include <stdio.h>
int (*workA) ( char *vA );
int (*workB) ( char *vB );
int main( int argc, char * argv[] )
{
char *strA = "Hello.";
char *strB = "Bonjour.";
int a = workA(strA);
int b = workB(strB);
printf("Return value of A = %d, B = %d.\n", a, b);
return 0;
}
int (*workA)( char *vA )
{
printf("A: %s\n", vA); // line 20
return 'A';
}
int (*workB)( char *vB )
{
printf("B: %s\n", vB); // line 27
return 'B';
}
GCC complains:
test.c:20: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
test.c:27: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
I don't know what's wrong with it. Any comments will be highly appreciated.
Upvotes: 0
Views: 203
Reputation: 145
When you write int (*workA) ( char *vA )
, it means that workA is a pointer to a function that returns an int. workA
is not a function.
Removing the parentheses around *workA
and simply writing int (*workA) ( char *vA )
makes workA
a function returning a pointer to an int, as required.
The same goes for workB.
You can use this great program called cdecl
to ease things up.
Upvotes: 0
Reputation: 4380
workA
and workB
are pointers to two functions. You need to declare actual functions that will do the work, then assign them to your two pointers before you call them...
#include <stdio.h>
int (*workA) ( char *vA );
int (*workB) ( char *vB );
int workAFunction( char *vA )
{
printf("A: %s\n", vA); // line 20
return 'A';
}
int workBFunction( char *vB )
{
printf("B: %s\n", vB); // line 27
return 'B';
}
int main( int argc, char * argv[] )
{
char *strA = "Hello.";
char *strB = "Bonjour.";
workA = workAFunction;
workB = workBFunction;
int a = workA(strA);
int b = workB(strB);
printf("Return value of A = %d, B = %d.\n", a, b);
return 0;
}
Upvotes: 2