Unnamed functions, functors or, more formally, function literals
Paul V. Andreev
sd70030@lanet.lv
Fri Mar 15 03:06:00 GMT 2002
On Thu, 14 Mar 2002, Rupert Wood wrote:
> I don't think it aids readability; to take your
> example, except rename the function "compare" to "compare_strings", then
> I consider:
>
> qsort(a,b,c, compare_strings);
>
> a lot more readable than your:
>
> qsort(a,b,c, (int (void *a1, void *a2)
> {return strcmp(*(char **)a1, *(char)**)a2);}));
>
> and a separate static function doesn't hurt much.
Of course, my example is too artificial. Now imagine a call to qsort is
nested deep inside some function. You have to define compare_strings at
top level, but use it somewhere deep inside some other function.
That is, usage is distantiated from definition, that may be too far for
big containing functions, which worsens readability.
But it mostly aids maintainability. To define and to use a function,
that is used only once, you would want to do it in one place.
Do you create "compare" functions for all seasons of life in your
global namespace? Now imagine you have to create a function to be used
only once. You have to create a distinguishing name, that don't clash
other names.
Think about C++ and STL. They were forced to predefine some functors, like
plus, minus and many others, but not all. To create other functors
one have to bother defining them at file scope level while they are
used at lower level.
Names are only needed for shared functions! Unnamed function could became
an idiom denoting "a helper function used only once".
> You may do better proposing it as a C++ extension, but I think you'll
> lose out there too; the syntax doesn't look clean from a typing point of
> view.
1) People need this feature, so it will appear soon or later.
2) Syntax is not more criptic than many other constructs in C.
> Your driver example; if you're writing multiple driver structures,
> though, you may want to share functions between them. I'd consider it
> more obvious to both programmer and compiler to have:
>
> struct driver
> {
> void foo();
> void bar();
> }
>
> void common_foo();
> void a_bar();
> void b_bar();
>
> struct driver a =
> {
> common_foo,
> a_bar
> };
>
> struct driver b =
> {
> common_foo,
> b_bar
> };
>
> than the inlined function alternative.
That's all OK what you are saying. Use named functions for shared ones,
but don't bother selecting appropriate names for nonshared ones (and
don't spoil your namespace).
Paul
More information about the Gcc
mailing list