Re: typedef function with void parameters
- From: jameskuyper@xxxxxxxxxxx
- Date: Thu, 13 Dec 2007 07:40:26 -0800 (PST)
William Xu wrote:
This won't compile:
,----
| int foo(char *p)
| {}
You've declared your function as returning an 'int', and then failed
to return anything. gcc will warn about these things; you should turn
the warning on. I normally use
gcc -ansi -pedantic -Wall -Wpointer-arith -Wcast-align -Wwrite-strings
-Wstrict-prototypes -Wmissing-prototypes
| int main(int argc, char *argv[])
| {
| typedef int (*FUNC)(void *);
|
| FUNC f = foo;
While it's no longer strictly necessary, I still think it's good
discipline to explicitly return a value from main(), too.
| }
`----
The error is:
,----
| gcc -O2 /Users/william/studio/helloworlds/foo.cpp -lm -o foo
| /Users/william/studio/helloworlds/foo.cpp: In function 'int main(int, char**)':
| /Users/william/studio/helloworlds/foo.cpp:26: error: invalid conversion from 'int (*)(char*)' to 'int (*)(void*)'
`----
It's perfectly legal to request that conversion, but it is not a
conversion that will occur implicitly. You have to perform an explicit
cast.
Note: the ONLY thing you can usefully do with the value of 'f' after
the conversion is convert it back to the original type, and then use
the restored function pointer to call the function. Here's a corrected
version:
int foo(char *p)
{ return 0; }
int main(int argc, char *argv[])
{
typedef int (*FUNC)(void *);
FUNC f = (FUNC)foo;
int (*g)(char*) = (int (*)(char*))f;
return g(argv[0]);
}
.
- Follow-Ups:
- Re: typedef function with void parameters
- From: William Xu
- Re: typedef function with void parameters
- References:
- typedef function with void parameters
- From: William Xu
- typedef function with void parameters
- Prev by Date: Re: Trouble with integer floating point conversion
- Next by Date: Re: Optimiser question
- Previous by thread: Re: typedef function with void parameters
- Next by thread: Re: typedef function with void parameters
- Index(es):
Relevant Pages
|