Re: get the address of a function??
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 01 Nov 2006 23:54:15 GMT
"John" <javacc1@xxxxxxxxx> writes:
Is the following program print the address of the function?
void hello()
{ printf("hello\n");
}
void main()
{
printf("hello function=%d\n", hello);
}
No.
"void hello()" is acceptable, but "void hello(void)" is better.
Calling printf with no visible prototype invokes undefined behavior.
The "#include <stdio.h>" is mandatory (even if your compiler doesn't
complain that it's missing).
main returns int, not void. If you learned "void main()" from a
textbook, stop using it and find a better one. The comp.lang.c FAQ is
at <http://www.c-faq.com/>; question 18.10 recommends some good books.
Make it "int main(void)".
printf's "%d" option requires an argument of type int. You're giving
it a function pointer. This invokes undefined behavior.
Since main returns int, you should return an int. Add "return 0;"
after your printf call. This isn't necessarily mandatory, but there's
no reason not to do it.
The printf format for a pointer value is "%p" -- but it can be used
*only* for object pointers, not for function pointers. Actually, "%p"
expects an argument of type void*, and since printf is a variadic
function, an ordinary pointer will not be implicitly converted to
void*; you have to do it yourself.
So the following will work to print the value of an object pointer:
int x;
int *ptr = &x;
printf("ptr = %p\n", (void*)ptr);
*But* there's no defined conversion from a function pointer to void*
(though some compilers may support it as an extension), so this won't
necessarily work for printing the address of your function.
(You can interpret a function pointer value as a sequence of bytes
(unsigned chars) and print their values, but I suspect that's more
than you want to deal with right now.)
Why do you want to do this? If you were to print the address of your
function, what would you do with the information?
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- get the address of a function??
- From: John
- get the address of a function??
- Prev by Date: Re: get the address of a function??
- Next by Date: Re: Question about C Functions
- Previous by thread: Re: get the address of a function??
- Next by thread: Re: get the address of a function??
- Index(es):
Relevant Pages
|
|