Xref: utzoo comp.lang.c++:13439 comp.lang.c:39281 Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!ncar!noao!arizona!dave From: dave@cs.arizona.edu (Dave Schaumann) Newsgroups: comp.lang.c++,comp.lang.c Subject: Re: Pointers to functions Message-ID: <1512@caslon.cs.arizona.edu> Date: 15 May 91 01:22:49 GMT References: Followup-To: comp.lang.c++ Organization: U of Arizona CS Dept, Tucson Lines: 75 In article aj3u@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@cs.arizona.edu | following it. - Niven's Law # 16