Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Passing values from structure arrays to a generic geometrical mean function Date: Sat, 28 Jan 2017 11:02:05 -0800 Organization: None to speak of Lines: 57 Message-ID: References: <971f7660-ee89-47b7-acde-1dc1e1ae2655@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="4f5353bf08e7d034cfc50822033a818b"; logging-data="27931"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18dOupo0GcEciEEY099Wh1H" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:hwgpSPLDY2qy5Gh7VoQCdWf8VUw= sha1:XoN4T+i2+pnVDBy1Pm9S7eQ74eg= Xref: csiph.com comp.lang.c:102652 Alla _ writes: > On Friday, January 27, 2017 at 10:48:29 PM UTC+3, Keith Thompson wrote: [...] >> You could also wrap the entire function definition in a macro >> definition, with macro parameters to specify the name of the structure >> type and of the double member. You'd have to invoke the macro for each >> structure type, creating a new function with a distinct name. >> > Do I include this macro as part of the function definition (as a parameter), > and then use specific struct types within a calling routine to pass those > to a function? No, the idea is that the macro would expand to an entire function definition, and you'd invoke the macro once for each structure type to define a function for that type. It's very similar to a C++ template, but much uglier and less type-safe. Here's a trivial (and not at all useful) example of what I'm talking about: #include #define DEFINE_INCREMENT_FUNCTION(type, name) \ void name(type *ptr) { \ *ptr ++; \ } DEFINE_INCREMENT_FUNCTION(int, inc_int) DEFINE_INCREMENT_FUNCTION(double, inc_double) int main(void) { int i = 3; inc_int(&i); double d = 4.5; inc_double(&d); printf("i = %d, d = %f\n", i, d); } This is not a good idea. This is an ugly approach that might become necessary in some circumstances. A similar approach is to define the function in a separate source file, and have the definition refer to several macros; you could then define those macros and #include the file. Note carefully that I am *not* recommending either approach. I'm just presenting alternatives that might become necessary if you need to deal with an existing set of data structures that don't allow for more straighforward code. [...] -- 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"