Path: csiph.com!optima2.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!newsfeed.straub-nv.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: declarator Date: Mon, 29 Jun 2015 19:01:16 -0700 Organization: None to speak of Lines: 81 Message-ID: References: <87d20eesim.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="18767"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18vAb+DwTyH6AJtYf3plZOw" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:HmjObaVtQHc8fSE7H3kyNkUtvF8= sha1:PbN2uK/D9+09RxYfMhhiBjCnpag= Xref: csiph.com comp.lang.c:64516 "Bill Cunningham" writes: > Ok here is just a quickie. Demonstrating the "function pointer." This is > sloppy because I did get these two warnings after compilation. And I know if > something was passed to the print wrapper function and the printf specifier > needed to be something other than %s there would be a problem. But this is > as I say just a quickie. Compiler warnings often indicate *serious* problems. That's not always the case, but it is here. > #include > > int print(char *); > int (*pf) (char *); Ok, pf is a pointer-to-function. > int main() > { > pf = print("hello there"); The print() function return a result of type int. You're trying to assign that int value to a function pointer. The name of a function, in an expression context, gives you the address of (i.e., a pointer to) the function. The name of a function followed by parentheses *calls* the function, and gives you the value returned by the function. If you want the pointer object pf to point to the function print, you need to do: pf = print; which is equivalent to: pf = &print; Once you've done that, you can use pf to call the function it points to: pf("hello there"); which is equivalent to: (*pf)("hello there"); > return pf; Now you're trying to return a pointer from main. Why? > } > > int print(char *input) > { > printf("%s\n", input); > return 0; > } > > And the warnings: > > p.c: In function 'main': > p.c:8:8: warning: assignment makes pointer from integer without a cast > [enabled by default] > pf = print("hello there"); > ^ > p.c:9:5: warning: return makes integer from pointer without a cast [enabled > by default] > return pf; > ^ > > I did not use -Wall either. as the compiler says "enabled by default. It > compiles and runs. gcc has an unfortunate habit of issuing non-fatal warnings for code that is unambiguously incorrect. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"