Pointers to functions
Dave Schaumann
dave at cs.arizona.edu
Wed May 15 11:22:49 AEST 1991
In article <AJ3U.91May14140642 at wilbury.cs.virginia.edu> aj3u at wilbury.cs.virginia.edu (Asim Jalis) writes:
>What is the difference between these two (pf is a pointer to a
>function, and hello is a function):
>
>pf = hello;
>
>and
>
>pf = &hello;
>
>The definitions for pf and hello are as follows:
>
>void (*pf)(); // pointer to a function
>
>void hello()
>{
> printf("Hello World\n");
>}
>
>I used the two different forms of assignments and got the same output.
>Is there a difference between them?
You have found one of the weirdnesses of ANSI-C. When you have a pointer
to a function, you (normally) invoke the function by saying
(*funptr)()
However, ANSI, in it's infinite wisdom, decided that you should be able to
say
funptr()
in the same context, with similar results.
---- Possible rationalization to follow ... press 'n' if you don't care ----
Actually, I believe this is probably due to an influence from C++, where you
have constructs called "classes" (which are similar in some ways to structs).
Suppose you have a class "foo", with an function called "foo_fn". Now, you
declare v to be a variable of class foo:
foo v ;
You now can invoke the function foo_fn on v in the following manner:
v.foo_fn()
(A pointer to v is an implicit variable in the function call)
This functionality can be mimiced in C in the following manner:
typedef struct FOO {
...
void (*foo_fn) ( struct FOO * ) c;
...
} foo ;
foo v ; /* assume that v.foo_fn is initialized appropriately */
Now, according to the traditional interpretation, you must say
(*v.foo_fn)(&v) ; /* A ptr to v must be explicitly passed */
To invoke foo_fn on v. The new interpretation allows you to say
v.foo_fn(&v) ;
Almost like C++ (almost since you still have to explicitly pass a
pointer to the invoking "variable" (known as "self" in C++)). Thus,
this feature allows you some measureof "poor man's C++" in ANSI C.
Of course, many of the nice features of C++ must be done by hand...
--
Dave Schaumann | There is no cause so right that one cannot find a fool
dave at cs.arizona.edu | following it. - Niven's Law # 16
More information about the Comp.lang.c
mailing list