473,668 Members | 2,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Anonymous functions in C.

Gnu C features some interesting extensions, among others
compound statements that return a value. For instance:

({ int y = foo(); int z;
if (y>0) z = y; else z=-y;
z;
})
A block enclosed by braces can appear within parentheses
to form a block that "returns" a value. This is handy
in some macros, or in other applications.

Actually this construct is nothing more (and nothing less)
than anonymous functions.

Anonymous functions could be really handy in call to qsort,
for instance, where just writing an expression could allow
the compiler to expand the anonymous function at each point of
call (as an inline function) within the qsort algorithm.

This, and other extensions are published in a document
"Potential Extnsions for Inclusion in a revision of
ISO/EIC 98/99" available at

http://www.open-std.org/jtc1/sc22/wg...docs/n1229.pdf

That is the official standard site.

Other Gnu extensions are mentioned in that document, like typeof
for instance, an extension that also lcc-win32 implements.
jacob
Apr 21 '07
60 5431
Richard Tobin a écrit :
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>No, GNU C's compound statements are not anonymous functions, because
they don't take arguments. How would you write a call to qsort()
using a compound statement in place of the compar argument? How would
the compound statement obtain the values to be compared?
The expressions take arguments from the local context, as far as the
implementation of gNU is concerned.

This is not fully anonymous functions but a step in that direction.
>I suppose GNU C's compound statements could be extended to act like
anonymous functions, but that's not what's being proposed.
Yes, it is not, but could be.
>
Anonymous functions are almost always going to be *nested* functions,
which opens the whole can of worms concerning non-local variables.
Can these functions refer to, and modify, variables in the containing
function? What happens if you return the functions to outside the
scope of the containing function?

GNU C already has nested (non-anonymous) functions, so they must have
addressed these questions.
As far as I remember their implementation is similar to pascal.
Nested functions take the environment where they are defined.
Apr 21 '07 #11
Richard Heathfield <rj*@see.sig.in validwrites:
For the record, AIUI the GNU syntax for this is that the compound
statement ends in a single expression whose value is taken as the value
of the whole statement, as the following code fragment (which is not
valid C) illustrates:

double area = { double a = r * r * pi; a; }

That's a lousy example, though, because it's so pointless. I spent a few
moments trying to think up a genuine use for these things, and didn't
manage it. Of course, that doesn't mean there isn't one.
AFAIK, those statements where introduced to allow #defining /inline/
functions, like:

#define max(a, b) ({ int _a = (a), _b = (b); _a < _b ? _b : _a; })

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >---<jid:mina86*chr ome.pl>--ooO--(_)--Ooo--
Apr 21 '07 #12
Michal Nazarewicz said:
Richard Heathfield <rj*@see.sig.in validwrites:
>For the record, AIUI the GNU syntax for this is that the compound
statement ends in a single expression whose value is taken as the
value of the whole statement, as the following code fragment (which
is not valid C) illustrates:

double area = { double a = r * r * pi; a; }

That's a lousy example, though, because it's so pointless. I spent a
few moments trying to think up a genuine use for these things, and
didn't manage it. Of course, that doesn't mean there isn't one.

AFAIK, those statements where introduced to allow #defining /inline/
functions, like:

#define max(a, b) ({ int _a = (a), _b = (b); _a < _b ? _b : _a; })
Well, this is another lousy example (sorry, Michal!) because it can be
done so easily in standard C:

#define max(a, b) (((a) (b)) ? (a) : (b))

I'm sure this proposed new syntax must have a use, but I'm still
struggling to find one.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 21 '07 #13
Richard Tobin a écrit :
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>I don't think variable names are an issue. A compound statement
creates a new scope, even if it's the result of a macro expansion.

But because names in a new scope can shadow outer ones, you have the
problem of inadvertent "variable capture", for example:

#define macro(x) {int t = (x)*2; ...}
...
int t;
macro(t+4);

There are obvious conventions to reduce the problem, but these are
likely to fail if you might have nested macro calls.

-- Richard
There is only one solution:
make real anonymous functions with arguments, etc.

How would they look like in C?

Apr 21 '07 #14
Richard Heathfield a écrit :
>
Well, this is another lousy example (sorry, Michal!) because it can be
done so easily in standard C:

#define max(a, b) (((a) (b)) ? (a) : (b))

I'm sure this proposed new syntax must have a use, but I'm still
struggling to find one.
Your example evaluates at least one argument twice. The example with the
GNU syntax doesn't.

Please read the contributions in this same thread
Apr 21 '07 #15
>Richard Heathfield <rj*@see.sig.in validwrites:
>>For the record, AIUI the GNU syntax for this is that the compound
statement ends in a single expression whose value is taken as the
value of the whole statement, as the following code fragment (which
is not valid C) illustrates:

double area = { double a = r * r * pi; a; }

That's a lousy example, though, because it's so pointless. I spent a
few moments trying to think up a genuine use for these things, and
didn't manage it. Of course, that doesn't mean there isn't one.
Michal Nazarewicz said:
>AFAIK, those statements where introduced to allow #defining /inline/
functions, like:

#define max(a, b) ({ int _a = (a), _b = (b); _a < _b ? _b : _a; })
Richard Heathfield <rj*@see.sig.in validwrites:
Well, this is another lousy example (sorry, Michal!) because it can be
done so easily in standard C:

#define max(a, b) (((a) (b)) ? (a) : (b))
And what about:

int i = 1, j = 0;
int k = max(++i, j);

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >---<jid:mina86*chr ome.pl>--ooO--(_)--Ooo--
Apr 21 '07 #16
jacob.navia said:
Richard Heathfield a écrit :
>>
Well, this is another lousy example (sorry, Michal!) because it can
be done so easily in standard C:

#define max(a, b) (((a) (b)) ? (a) : (b))

I'm sure this proposed new syntax must have a use, but I'm still
struggling to find one.

Your example evaluates at least one argument twice. The example with
the GNU syntax doesn't.
That is certainly true, but irrelevant unless the caller is abusing the
preprocessor by using macro arguments which oughtn't to be evaluated
more than once. If the motivation for anonymous functions is simply to
make it possible to abuse the preprocessor in comfort, then I don't see
the value. No doubt there are better uses.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 21 '07 #17
Michal Nazarewicz said:
>>Richard Heathfield <rj*@see.sig.in validwrites:
For the record, AIUI the GNU syntax for this is that the compound
statement ends in a single expression whose value is taken as the
value of the whole statement, as the following code fragment (which
is not valid C) illustrates:

double area = { double a = r * r * pi; a; }

That's a lousy example, though, because it's so pointless. I spent
a few moments trying to think up a genuine use for these things,
and didn't manage it. Of course, that doesn't mean there isn't one.
>Michal Nazarewicz said:
>>AFAIK, those statements where introduced to allow #defining /inline/
functions, like:

#define max(a, b) ({ int _a = (a), _b = (b); _a < _b ? _b : _a; })

Richard Heathfield <rj*@see.sig.in validwrites:
>Well, this is another lousy example (sorry, Michal!) because it can
be done so easily in standard C:

#define max(a, b) (((a) (b)) ? (a) : (b))

And what about:

int i = 1, j = 0;
int k = max(++i, j);
Understood (multiple eval), but frankly I wouldn't go adding an entire
new language feature just to make extra work for myself when I can
already write this as:

int i = 2, j = 0, k = 2;

and in any case, the C community already knows not to risk such
expressions as yours when using macros. Are we going to muddy the
waters by introducing a language feature which makes it okay sometimes,
provided you're careful in the #define?

I don't see that as a win.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 21 '07 #18
>Richard Heathfield a écrit :
>>>
Well, this is another lousy example (sorry, Michal!) because it can
be done so easily in standard C:

#define max(a, b) (((a) (b)) ? (a) : (b))

I'm sure this proposed new syntax must have a use, but I'm still
struggling to find one.
jacob.navia said:
>Your example evaluates at least one argument twice. The example with
the GNU syntax doesn't.
Richard Heathfield <rj*@see.sig.in validwrites:
That is certainly true, but irrelevant unless the caller is abusing the
preprocessor by using macro arguments which oughtn't to be evaluated
more than once.
AFAIK that was the reason this syntax was introduced in GCC (though I
may be wrong).
If the motivation for anonymous functions is simply to
make it possible to abuse the preprocessor in comfort, then I don't see
the value. No doubt there are better uses.
Certainly it wouldn't make sens to introduce anonymous functions just
to allow abusing preprocessor as we have inline functions in C99.

IMO there's not much use for them anyway. The only thing I can think
of is:

qsort(array, sizeof array / sizeof *array, sizeof *array,
({ some kind of strange syntax }));

and it's not like one uses callback functions every 10th line of code.

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >---<jid:mina86*chr ome.pl>--ooO--(_)--Ooo--
Apr 21 '07 #19
Michal Nazarewicz said:

<snip>
Certainly it wouldn't make sens to introduce anonymous functions just
to allow abusing preprocessor as we have inline functions in C99.
Agreed.
IMO there's not much use for them anyway. The only thing I can think
of is:

qsort(array, sizeof array / sizeof *array, sizeof *array,
({ some kind of strange syntax }));
Interesting. Perhaps something like this:

{ :formal parameter list: { body goes here } value; }
and it's not like one uses callback functions every 10th line of code.
Yeah, this does look like a solution looking for a problem.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 21 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2060
by: Carlos Ribeiro | last post by:
I thought about this problem over the weekend, after long hours of hacking some metaclasses to allow me to express some real case data structures as Python classes. I think that this is something with potential to be useful, but I would like to hear more opinions first. If this is deemed to be useful, I *may* try to write a PEP for it. This is not a promise or even a proposal, at this point. Broadly generalizing, classes in Python have...
76
3764
by: Nick Coghlan | last post by:
GvR has commented that he want to get rid of the lambda keyword for Python 3.0. Getting rid of lambda seems like a worthy goal, but I'd prefer to see it dropped in favour of a different syntax, rather than completely losing the ability to have anonymous functions. Anyway, I'm looking for feedback on a def-based syntax that came up in a recent c.l.p discussion:...
6
3444
by: Mark Brandyberry | last post by:
I have a bit of a problem with an overloaded operator that I'm writing that I have distilled down to an example in the code below. Essentially, I have an operator function (+=) that takes a reference parameter of class Poly. If I use it with a named object (of type Poly), as in: P1+=P4; where P1 and P4 are both local variables of the class type, it works fine. If I try to use an anonymous object on the right side, then I get an error...
6
6981
by: Gaijinco | last post by:
I have always felt that there are a lot of topics that you learned the facts but you only grasp the matter sometime down the road. For me, two of those topics are inner classes and anonymous classes. I was thinking of a class Agenda. For it I would use a class Person which also uses another class Date for her birthday. When I was modeling Person, I made an atribute to be an object of class Date. Suddenly I thought that maybe it was a...
7
2860
by: Gregor Kofler | last post by:
What is the best practice for removing anonymous functions? Something like (function() { doSomething(); arguments.callee = null; })(); seems to work (at least it triggers no errors or exceptions on FF, but is this really a working solution?
22
3912
by: Luna Moon | last post by:
I am reading the book "C++ Annotations", and here is a quote from the book: Namespaces can be defined without a name. Such a namespace is anonymous and it restricts the visibility of the defined entities to the source file in which the anonymous namespace is defined. Entities defined in the anonymous namespace are comparable to C’s static functions and variables. In C++ the static keyword can still be used, but its use is more
0
8459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8890
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8577
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7398
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6206
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5677
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2786
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2018
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1783
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.