[comp.lang.c++] Functions as arguments

robert@pvab.UUCP (Robert Claeson) (08/13/87)

I have trouble taking the address of a function, sending that address
as an argument to a function, declaring that argument as a function
address in the called function and then call the function pointed-to
by the address. What is the correct way to do this? The usual C way
doesn't work. We have C++ 1.1.


-- 
SNAIL:	Robert Claeson, PVAB, P.O. Box 4040, S-171 04 Solna, Sweden
UUCP:	{seismo,mcvax,munnari}!enea!pvab!robert
ARPA:	enea!pvab!robert@seismo.arpa

guy@gorodish.UUCP (08/15/87)

> I have trouble taking the address of a function, sending that address
> as an argument to a function, declaring that argument as a function
> address in the called function and then call the function pointed-to
> by the address. What is the correct way to do this? The usual C way
> doesn't work. We have C++ 1.1.

I tried the following:

1	#include <stdio.h>
2
3	static int
4	func1(int x)
5	{
6		return x + 1;
7	}
8
9	static int
10	func2(int (*funcp)(int x))
11	{
12		return (*funcp)(33);
13	}
14
15	int
16	main(int argc, char **argv)
17	{
18		(void) printf("%d\n", func2(func1));
19	}

with C++ 1.1 and "cfront" got very upset, giving no less than 3 syntax errors
on line 10, one on line 11, three on line 12, and 1 on line 13.  However,
replacing "func2" with

	static int
	func2(funcp)
	int (*funcp)(int x);
	{
		return (*funcp)(33);
	}

replaced all those complaints with one warning of an "old style definition of
func2()", and yielded a program that correctly printed "34".

I can see nothing syntactically wrong with the first definition of "func2".
Looks like a "cfront" bug to me....
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy@sun.com

ark@alice.UUCP (08/16/87)

In article <25710@sun.uucp>, guy@gorodish.UUCP writes:
> 1	#include <stdio.h>
> 2
> 3	static int
> 4	func1(int x)
> 5	{
> 6		return x + 1;
> 7	}
> 8
> 9	static int
> 10	func2(int (*funcp)(int x))
> 11	{
> 12		return (*funcp)(33);
> 13	}
> 14
> 15	int
> 16	main(int argc, char **argv)
> 17	{
> 18		(void) printf("%d\n", func2(func1));
> 19	}
> 
> with C++ 1.1 and "cfront" got very upset, giving no less than 3 syntax errors
> on line 10, one on line 11, three on line 12, and 1 on line 13.

Yep, it's a bug all right.  Two ways around it.  First, change

	static int func2(int (*funcp)(int x))

to

	static int func2(auto int (*funcp)(int x))

Second possibility is to define a type:

	#include <stdio.h>

	static int
	func1(int x)
	{
		return x + 1;
	}

	typedef int (*FUNCPTYPE) (int);

	static int
	func2(FUNCPTYPE funcp)
	{
		return (*funcp)(33);
	}

	int
	main(int argc, char **argv)
	{
		(void) printf("%d\n", func2(func1));
	}

In both cases, you will get warnings that argc and argv
aren't used.  If you don't use them, you needn't metion them:

	int
	main(int, char **)
	{
		(void) printf("%d\n", func2(func1));
	}