473,804 Members | 4,795 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 5478
Richard Tobin wrote:
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.
Correct me if I'm wrong (it's been known to happen ...),
but I think there's no problem with the example shown. The
scope of the "inner" t begins at the end of its declarator
(6.2.1/7), and the initialization is part of the declarator
(6.7/1). Therefore, in the expanded `int t = (t + 4) * 2;'
the initializer's t refers to the "outer" variable, not to the
variable being initialized.

--
Eric Sosman
es*****@acm-dot-org.invalid
Apr 21 '07 #21
Eric Sosman wrote:
Richard Tobin wrote:
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.

Correct me if I'm wrong (it's been known to happen ...),
but I think there's no problem with the example shown. The
scope of the "inner" t begins at the end of its declarator
(6.2.1/7), and the initialization is part of the declarator
(6.7/1).
The initialization part is not part of the declarator. The grammar
(6.7/1) reads:

init-declarator:
declarator
declarator = initializer

The initializer is part of "init-declarator", which is a combination
of a declarator and an initializer. The initializer is not part of the
declarator itself.

Apr 21 '07 #22
Harald van Dijk wrote:
Eric Sosman wrote:
>Richard Tobin wrote:
>>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.
Correct me if I'm wrong (it's been known to happen ...),
but I think there's no problem with the example shown. The
scope of the "inner" t begins at the end of its declarator
(6.2.1/7), and the initialization is part of the declarator
(6.7/1).

The initialization part is not part of the declarator. The grammar
(6.7/1) reads:

init-declarator:
declarator
declarator = initializer

The initializer is part of "init-declarator", which is a combination
of a declarator and an initializer. The initializer is not part of the
declarator itself.
Thanks for the correction. The grammar seems clear enough,
but the wording in 6.7/6 seems unclear:

"[...] The init-declarator-list is a comma-separated
sequence of declarators, each of which may have [...]
an initializer [...]"

I was reading "have" as "incorporat e" or "subsume," but in light
of the grammar I guess it must mean "be accompanied by."

--
Eric Sosman
es*****@acm-dot-org.invalid

Apr 21 '07 #23
Richard Heathfield a écrit :
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.
As you may know, macros and function calls are not
easy to distinguish in C.

You HAVE TO KNOW that you are calling a macro and not a function.
You may know that, or you may not.

What is important for language coherence and transparency is that

foo(i++);

evaluates i only once if it is a macro or not.
Apr 21 '07 #24
Harald van Dijk <tr*****@gmail. comwrites:
Keith Thompson wrote:
>ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
[...]
Without going that far, one obvious use is in macros, since it allows
you introduce new variables in the macro expansion. Of course, you
then run into the question of what's a safe name for those variables
(in Lisp, you traditionally use gensym to generate a variable name,
but that requires a more powerful macro language). Many of the macro
uses can be more cleanly solved with inline functions, but others
depend on being able to access variables that aren't arguments to the
function or macro.

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.

#define my_abs(x) ({ int y = x; y 0 ? y : -y; })

would fail if called as my_abs(y).
You're right.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 21 '07 #25
"jacob.navi a" <ja***@jacob.re mcomp.frwrites:
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.

There is only one solution:
make real anonymous functions with arguments, etc.
There is another solution: use ordinary functions (inline if you
like).
How would they look like in C?
No idea.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 21 '07 #26
jacob.navia said:

<snip>
As you may know, macros and function calls are not
easy to distinguish in C.
It is generally quite simple to find out, if you have decent tools, but
I agree that they are superficially similar in appearance.
You HAVE TO KNOW that you are calling a macro and not a function.
Yes, you do.
You may know that, or you may not.
If you don't, you need to find out.
What is important for language coherence and transparency is that

foo(i++);

evaluates i only once if it is a macro or not.
Nevertheless, the risk exists that it may be evaluated more than once,
and this is well-known within the community. Introducing this new
language feature will not eliminate the risk.

--
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 #27
>>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))
Michal Nazarewicz said:
>int i = 1, j = 0;
int k = max(++i, j);
Richard Heathfield <rj*@see.sig.in validwrites:
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'm not saying we should add this feature. I'm explaining what's it
all about.

--
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 #28
Richard Heathfield wrote:
Michal Nazarewicz said:
.... snip ...
>
>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))
Doesn't work very well when a and/or b have side effects.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfoc us.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline.net
--
Posted via a free Usenet account from http://www.teranews.com

Apr 21 '07 #29
In article <f0***********@ pc-news.cogsci.ed. ac.uk>,
Richard Tobin <ri*****@cogsci .ed.ac.ukwrote:
>
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?
Yes they can. The containing function passes its own frame pointer as an
extra hidden argument to the nested function.
What happens if you return the functions to outside the
scope of the containing function?
That's very similar to returning a pointer to an auto variable. The return
doesn't extend the lifetime of the thing being referenced. When you try to
call the nested function through that returned pointer, the GCC manual warns
us: "all hell will break loose".

A pointer to a nested function is actually 2 pointers: a pointer to the code
and a copy of the frame pointer of the corresponding instance of the
containing function. Whenever a pointer to a nested function is required, a
wrapper function is dynamically created to encapsulate those 2 pointers.
Passing this wrapper-pointer down to qsort works fine, but you can't return
it. Not only does it require the use of the containing function's local
variables which are now dead, the wrapper function (trampoline) itself died
along with them.

--
Alan Curry
pa****@world.st d.com
Apr 21 '07 #30

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

Similar topics

0
2069
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
3807
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
3452
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
6990
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
2874
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
3941
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
9706
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
10577
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...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10077
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7620
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
5521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4299
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
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
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.