473,695 Members | 2,878 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Nested functions in c++?

Hello,
code like this:

int f1(int x){
int f2(int y){
return y*y;
}

if(x > 0)
return f2(x);
else
return -1;
}
is invalid. functions cannot have nested functions in c++. I read
comparison d vs other programming languages
http://www.digitalmars.com/d/comparison.html
it says that d has nested functions and other s don't. But I always
used a construct that gives effect of nested function, and I'd like to
ask if such code is valid according to the standard.

int f1(int x){
struct {
int operator()(int y){ return y*y; }
} f2;

if(x > 0)
return f2(x);
else
return -1;
}

Thanks

Jul 23 '05 #1
7 2246
bl******@mail.r u wrote:
code like this:

int f1(int x){
int f2(int y){
return y*y;
}

if(x > 0)
return f2(x);
else
return -1;
}
is invalid. functions cannot have nested functions in c++.
[...potential flame bait removed...] I always
used a construct that gives effect of nested function, and I'd like to
ask if such code is valid according to the standard.

int f1(int x){
struct {
int operator()(int y){ return y*y; }
} f2;

if(x > 0)
return f2(x);
else
return -1;
}


The code is valid.

Nested functions sometimes have other properties (qualities) that local
classes don't, like access to all automatic variables declared in the
scopes surrounding the one that contains the function. You cannot easily
achieve that with local classes. Of course, the usefulness of being able
to access "automatic" variables depends on whether you actually need it.
And apparently, all C++ programmers learned to live without it.

V
Jul 23 '05 #2
* bl******@mail.r u:
... I always
used a construct that gives effect of nested function, and I'd like to
ask if such code is valid according to the standard.

int f1(int x){
struct {
int operator()(int y){ return y*y; }
} f2;

if(x > 0)
return f2(x);
else
return -1;
}


Yes, although for efficiency I wouldn't code it like that.

It's not quite the same as a nested function in a language like e.g. Pascal.

Most important, the local class' members don't have access to the outer
function's arguments.

Second, the local class has internal linkage, and so cannot be used as a
template argument, and that also goes for the class members.

Third (although that has nothing to do with nested functions), AFAIK there's no
way to provide out-of-class definitions of members of a local class.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #3

<bl******@mail. ru> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
Hello,
code like this:

int f1(int x){
int f2(int y){
return y*y;
}

if(x > 0)
return f2(x);
else
return -1;
}
is invalid. functions cannot have nested functions in c++. I read
comparison d vs other programming languages
http://www.digitalmars.com/d/comparison.html
it says that d has nested functions and other s don't. But I always
used a construct that gives effect of nested function, and I'd like to
ask if such code is valid according to the standard.

int f1(int x){
struct {
int operator()(int y){ return y*y; }
} f2;

if(x > 0)
return f2(x);
else
return -1;
}


Yes, it is valid. But it lacks the point of a true nested function - being
able to access the local variables of the enclosing function:

int f1(int x){
int f2(int y){
return x*y; // note we're accessing parameter 'x' here
}

if(x > 0)
return f2(x);
else
return -1;
}

C++ programs often emulate this behavior using either macros or by passing
references to local variables as extra parameters to f2(). But having a true
nested function capability makes the code cleaner and more straightforward
to write.
Jul 23 '05 #4
They have some support for accessing local variables of outer functions
in Boost called Adaptive Closures. This of course is not the same as
with nested functions, but allows you to get access to some variables of
the outer stack frame (especially useful when you can't change the
signature).

Here is the link to read more:
http://www.boost.org/libs/spirit/pho..._closures.html

Yuriy

Walter wrote:
<bl******@mail. ru> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
Hello,
code like this:

int f1(int x){
int f2(int y){
return y*y;
}

if(x > 0)
return f2(x);
else
return -1;
}
is invalid. functions cannot have nested functions in c++. I read
comparison d vs other programming languages
http://www.digitalmars.com/d/comparison.html
it says that d has nested functions and other s don't. But I always
used a construct that gives effect of nested function, and I'd like to
ask if such code is valid according to the standard.

int f1(int x){
struct {
int operator()(int y){ return y*y; }
} f2;

if(x > 0)
return f2(x);
else
return -1;
}

Yes, it is valid. But it lacks the point of a true nested function - being
able to access the local variables of the enclosing function:

int f1(int x){
int f2(int y){
return x*y; // note we're accessing parameter 'x' here
}

if(x > 0)
return f2(x);
else
return -1;
}

C++ programs often emulate this behavior using either macros or by passing
references to local variables as extra parameters to f2(). But having a true
nested function capability makes the code cleaner and more straightforward
to write.


Jul 23 '05 #5

"Yuriy Solodkyy" <so*****@tamu.p ut_edu_here> wrote in message
news:d4******** **@news.tamu.ed u...
They have some support for accessing local variables of outer functions
in Boost called Adaptive Closures. This of course is not the same as
with nested functions, but allows you to get access to some variables of
the outer stack frame (especially useful when you can't change the
signature).

Here is the link to read more:
http://www.boost.org/libs/spirit/pho..._closures.html


Thanks for the link. What that does is move the declarations of locals into
a local class, and then presumably a pointer to that class is passed into
the 'nested' function. While I've used this technique, it's only a half
solution (doesn't do parameters) and is complex and obtuse to use.
Jul 23 '05 #6
Thanks for answers, and links.
When I posted my message I didn't think about accessing local
variables, so this is't really nested function. I good article about
that I found: http://www.gotw.ca/gotw/058.htm

I only have a question to Alf:
Yes, although for efficiency I wouldn't code it like that.


How then would you code this place? with #define's? For such simple
case compiler optimization will result in the equivalent code like the
following:
int f1(int x){
if(x > 0)
return x*x;
else
return -1;
}

Jul 23 '05 #7
* pa**********@gm ail.com:
Thanks for answers, and links.
When I posted my message I didn't think about accessing local
variables, so this is't really nested function. I good article about
that I found: http://www.gotw.ca/gotw/058.htm

I only have a question to Alf:
Yes, although for efficiency I wouldn't code it like that.


How then would you code this place? with #define's? For such simple
case compiler optimization will result in the equivalent code like the
following:
int f1(int x){
if(x > 0)
return x*x;
else
return -1;
}


As a rule, don't rely on compiler optimizations when you can express what
you want in code. For example, use const& arguments for strings etc. instead
of relying on compiler optimization. In such cases, and in this case,
optimization considerations can indicate more _natural_ ways to write the
code, ways that more directly reflect the intended effect:

int f( int x )
{
struct local
{
static int square( int x ) { return x*x; }
};

return (x > 0? local::square( x ) : -1);
}

Here there is no unused implicit argument to function 'square'.

However, it's probably Bad Advice to tell people to think about optimization,
because in most cases those who think optimization end up with code that's not
just unnatural, extremely complicated and inefficient, but also plain wrong...

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #8

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

Similar topics

3
2339
by: Nils Grimsmo | last post by:
hi, i'm having some trouble nesting functions. consider the following: def h(): x = 1 def g(): print x # ok, x is taken from h g()
6
2566
by: Andy Baker | last post by:
Hi there, I'm learning Python at the moment and trying to grok the thinking behind it's scoping and nesting rules. I was googling for nested functions and found this Guido quote: (http://www.python.org/search/hypermail/python-1993/0343.html) "This is because nested function definitions don't have access to the local variables of the surrounding block -- only to the globals of the
6
12197
by: A | last post by:
Hi, How do you make use of nested functions in C++? I realize in C++ that everything must be declared first in a header file before implementation in a .cpp file. I tried to nest a method prototype in another prototype but seems pointless. Can someone please write a short, simple, and concise skeleton code of how to use nested functions? class Foo {
2
7510
by: Forgone Conclusion | last post by:
Hi, I have a View that groups and sums up totals. This View is then nested within in another View and used (it needs to be done like this). What i need to do is to be able to vary the records in the nested query by specifying dates. These would somehow need to be passed to the nested query. I've looked into stored procedures/functions but am still stumped on
10
3227
by: nimmi_srivastav | last post by:
Below you will see an example of a nested conditional expression that this colleague of mine loves. He claims that it is more efficient that a multi-level if-else-if structure. Moreover, our complexity analyzer tool supposedly does not pick it up. Is it really more efficient? Personally I find this coding style extremely cryptic, misleading and error-prone. I believe that I have removed all traces of proprietary-ness from this coding...
9
2842
by: Gregory Petrosyan | last post by:
I often make helper functions nested, like this: def f(): def helper(): ... ... is it a good practice or not? What about performance of such constructs?
4
2312
by: Wolfgang Draxinger | last post by:
If you know languages like Python or D you know, that nested functions can be really handy. Though some compilers (looking at GCC) provide the extension of nested functions, I wonder, how one could implement an equivalent behaviour with plain C (in this case I'm thinking of the language I'm developing, which shall be converted into C for target compilation). So far I didn't touch the topic "nested functions", since I just don't see an...
2
1663
by: Johannes Bauer | last post by:
Nick Keighley schrieb: Why is there actually a *need* for nested functions? If functionality of subfunctions which are only locally visible is desired, why not put the nesting function parent and its nested children all in one module, declare the children static - voila. Std-C. Regards, Johannes
9
3987
by: Gabriel Rossetti | last post by:
Hello, I can't get getattr() to return nested functions, I tried this : .... def titi(): .... pass .... f = getattr(toto, "titi") .... print str(f) .... Traceback (most recent call last):
0
9112
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
8971
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...
1
8824
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
8817
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...
0
7651
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
6484
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
4336
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...
2
2258
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1970
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.