TweetFollow Us on Twitter

August 91 - How to Cope with Nesting Instinct (in C++)

How to Cope with Nesting Instinct (in C++)

Eric M. Berdahl

MacApp 3 will add large amounts of spice to programming recipes. There are new classes, new twists on old classes, and new hoops to jump through.

However, the more interesting items are from the primary language of implementation changing from Pascal to C++. In fact, I propose that MacApp 3's best features are its solutions to the so-called "Nested Procedure" problem.

As a software author, I spend a fair amount of time listening to a short description of some problem a user is having and a longer description of what the user wants to do to solve it. Sound familiar? Sometimes the user is right on the money as to the nature of the "right" solution, but more often it is their description of the problem that is most revealing. I view the Nested Procedure problem in that light. I don't necessarily want nested procedural constructs, but I do have a problem to solve.

One solution is to implement language support for grouping sets of code in some logical order. The Pascal language provides this. However, it's not the only solution, nor is it the only solution for the MacApp programmer-at least not for the ones who use C++.

This article will examine the nested procedure problem, look for solutions, and discuss what this has to do with MacApp. First, I'll describe the problem in more detail. This may seem obvious and repetitive, but the goal is to come up with something that does what nested procedures in Pascal do. In addition, the solution should be link compatible with Object Pascal.

SCOPES?

Let's examine some textbook descriptions of Pascal. Pascal lore provides many ideas from which one may leverage; one of the most useful is the concept of scopes.

Simply put, a scope is the range over which a coding entity-variable, constant, or routine-is meaningful. Languages like assembly generally recognize only one scope, global. That is, once you get down to the assembly level, everything is visible to everyone all the time.

Moving up one step, there is C. C recognizes two basic scopes, global and local. That is, something is either scopeless-global-or it exists within a specific routine.

Languages like Pascal maintain a highly ordered, scoped hierarchy. Pascal's description of scoping is so good, in fact, that to many people, Pascal's implementation is scoping.

ABRACADABRA!

You might ask, at this point, "But when I write Pascal code, I don't really have to worry about scopes, do I?"

Probably not, but you do have to be careful. For example, many of you may remember something like the code in Listing 1 from a Computer Science 101 test. The exam would quiz you on the output of the program; to answer correctly, you would have to recognize that there are overlapping scopes and resolve them appropriately.

In a more practical world, you might see something like Example 2. Example 2 calls a procedure, DoSomethingToIntegers, telling it what action it wants performed, namely DoToInteger. Furthermore, DoToInteger has some magic knowledge of the local variables, oneInt and twoInt. Pascal accomplishes this by giving the nested procedure, DoToInteger, an additional parameter referred to as a "static link" variable. The static link is a pointer to the stack frame of the enclosing routine.

Thus, when a Pascal nested procedure is called, a pointer to the routine's stack frame is passed as a hidden argument. Also, when a routine is passed as a procedure parameter to a Pascal routine, as is done with DoToInteger, a pointer to the routine's stack frame is passed as an additional parameter. In the example, DoSomethingToIntegers actually takes two parameters, the routine to execute, DoToInteger, and a value to pass as the static link parameter to the indicated routine.

OH, I C

A person emulating this concept in a C-based language could write something like Example 3. This construct directly translates Pascal's mechanism into C's. It also looks ugly. For some reason, Pascal's elegance has been lost. Pascal deals elegantly with the static link problem; as a programmer, I don't need to deal with it. I just write my code and let Pascal take care of the overhead.

In Example 3, you could just pass DoSomethingToIntegers a pointer to oneInt, and have CBasedDoToInteger know that staticLink is a pointer to a short, namely oneInt. But that means it won't know about twoInt! Alternatively, you could define a structure that holds oneInt and twoInt, and pass a pointer to the structure for the static link, but that's unattractive. Clearly, it's better to refine and generalize the solution.

DOING IT right IN C++

Simple emulation doesn't seem to solve the nested procedure problem. Nonetheless, Pascal has provided a good starting point, and later we'll return to it. For the moment, however, let's look at another avenue-object technology. Regardless of the language to which it is bound, object concepts provide the programmer with another layer of scoping.

The key to an object-based approach is to recognize that, implicitly, a method is scoped to exist within an instance of an object. I tend to avoid hard-core C++ documentation (except during psychotically masochistic episodes), but in most C++ texts, the descriptions of objects as scopes-and the implications of this for visualizing program constructs-are very good.

For the problem above, a class could be defined, like CDoToInteger in Example 4, to handle the hard work. CDoToInteger looks much closer to what's desired than CBasedDoToInteger in Example 3.

"But where did the mystical staticLink parameter go?" the intrepid reader asks. It's hidden by the magic of object programming, just as it was hidden by the magic of Pascal in the Pascal example. In the object programming case, the scope is determined by the implicit variable this (SELF for you Pascal fans, Current for you Eiffel fans).

Look again at CPlusFoo in Example 4 to see how the CDoToInteger class might be used. I've indicated a routine to invoke-CPlusDoToInteger in the scope of CDoToInteger-and indicated a context in which to execute the routine, aScope. That's it, right?

Not quite. I still have to find some way for aScope to know about oneInt and twoInt within CPlusFoo. One solution might be to set the individual instance variables of aScope to hold the same values as the local variables of CPlusFoo, but that's not what I really want. I want the oneInt and twoInt variables of CDoToInteger to be pointers to oneInt and twoInt in CPlusFoo, but I also need to ensure that those pointers are never nil.

This is the second and last reason that to reasonably use reference variables in C++ MacApp code. (The first involved parameter passing, and was discussed last issue.) So, the CDoToInteger class is finished in Example 5. The careful reader will notice that the declaration of CPlusDoToInteger changed subtly in this last revision. It now carries a Pascal calling sequence, so that it's compatible with Pascal. The difference here is the order in which parameters on the stack are evaluated. The declaration above indicates that the magic this parameter is to be the last parameter pushed on the stack, just like the Pascal magic static link is pushed on last. Ta da.

A PRACTICAL EXAMPLE

So, how might one use such information in a real MacApp application? Consider a common situation, that of iterating over items in a TList:
class CCountSubViews {
private:
long&           numberOfViews;
public:
    CCountSubViews(long& aNumberOfViews) :
    numberOfViews(aNumberOfViews) { }

    pascal void CountSubViews(TView* aView)
   {
    numberOfViews++;
   }
};

pascal void TMyView::CountSubViews()
{
   long             numberOfSubViews;
   CCountSubViews   aCounter(numberOfSubViews);
   fSubViews->Each(CCountSubViews::CountSubViews,
                          &aCounter);
}

You can come up with more relevant examples, I'm sure, but I chose this particular example for a reason. Each is a method that allows a routine to iterate over the items in a TList. This can be used with the magic of Pascal and nested procedures; however, MacApp 3 provides C++ users with another way to iterate.

ITERATORS

Often the best way to solve a problem is to avoid it. It would be nice to avoid writing helper classes, and just bring iteration into the mainstream of code. After all, anyone is used to iterating over integers and other built-in types with simple for loops:
// Find the sum of all integers on the interval [0..4]
short   a;
a = 0;
for (short i = 0; i < 5; i = i + 1)
{
    

a = a + i; }

MacApp 3 provides a nice mechanism for doing this-iterators. A library of iterator objects (sorry, C++ users only) is available for doing a variety of iterative actions. The following is an example of CObjectIterator, the class for iterating over objects in a TList:

CObjectIterator    iter(aTList);
for (TObject* anOb = iter.FirstObject(); iter.More();
    anOb = iter.NextObject())
{
    //  do something with anOb here
}

Within the body of the loop, you can manipulate anOb just as you would any local variable. The reason for this is that anOb is a full-fledged local variable. So, if you happen to know that aTList only contains instances of TFoo, you can easily (and legally) cast anOb to TFoo*.

Iterator classes are provided for most of the basic iterations. For example, the CSubViewIterator class, iterates over each subview of a given TView. You might use it in the following fashion:

CSubViewIterator   iter(aTView);
for (TView* aView = iter.FirstSubView(); iter.More(); aView = iter.NextSubView())
{
    //  do something with aView here
}

NEXT TIME…

Next issue, I'll look at the wild and woolly world of MacApp 3. I'll show what new functionality it provides, what you might want to tap into right away, and what you'll want to study first. Keep those cards and letters coming!

Tech Note #265

For more information on Pascal PROCEDURE parameters, I refer the inquisitive reader to Tech Note #265: Pascal to C - PROCEDURE parameters. n
 
AAPL
$102.57
Apple Inc.
+0.32
MSFT
$45.09
Microsoft Corpora
+0.21
GOOG
$570.78
Google Inc.
+1.58

MacTech Search:
Community Search:

Software Updates via MacUpdate

VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more
LibreOffice 4.3.1.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
SlingPlayer Plugin 3.3.20.505 - Browser...
SlingPlayer is the screen interface software that works hand-in-hand with the hardware inside the Slingbox to make your TV viewing experience just like that at home. It features an array of... Read more
Get Lyrical 3.8 - Auto-magically adds ly...
Get Lyrical auto-magically add lyrics to songs in iTunes. You can choose either a selection of tracks, or the current track. Or turn on "Active Tagging" to get lyrics for songs as you play them.... Read more
Viber 4.2.2 - Send messages and make cal...
Viber lets you send free messages and make free calls to other Viber users, on any device and network, in any country! Viber syncs your contacts, messages and call history with your mobile device,... Read more
Cocktail 7.6 - General maintenance and o...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
LaunchBar 6.1 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
BBEdit 10.5.12 - Powerful text and HTML...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more

Latest Forum Discussions

See All

The Walking Dead Pinball Review
The Walking Dead Pinball Review By Blake Grundman on August 29th, 2014 Our Rating: :: DECISIONS, DECISIONS...Universal App - Designed for iPhone and iPad Zen Studios is at it again, taking a property that would never seem to work... | Read more »
Stupeflix Has Released a Major Update fo...
Stupeflix Has Released a Major Update for Replay Posted by Jessica Fisher on August 29th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
ALONE… Review
ALONE… Review By Jennifer Allen on August 29th, 2014 Our Rating: :: MINIMALISTIC AND TOUGHUniversal App - Designed for iPhone and iPad Tough yet satisfying, ALONE… is a challenging endless flyer with some suitably sensitive... | Read more »
Hyperlapse Review
Hyperlapse Review By Jennifer Allen on August 28th, 2014 Our Rating: :: SPEEDY VIDEO SNAPSUniversal App - Designed for iPhone and iPad Want to make a great time-lapse video quickly? Hyperlapse is perfect for that.   | Read more »
Back To Bed Review
Back To Bed Review By Jennifer Allen on August 28th, 2014 Our Rating: :: STYLISH BUT LIMITEDUniversal App - Designed for iPhone and iPad It looks gorgeous, but Back to Bed is actually a fairly simple and uneventful puzzle game.   | Read more »
New Cars, New Locations, and a New Seaso...
New Cars, New Locations, and a New Season in Asphalt 8: Airborne Update Posted by Jessica Fisher on August 28th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Award Winning Children’s Book Bedtime fo...
Bedtime for Sarah Sullivan is a children’s storybook that emphasizes the importance of going to bed, dreams, and those magical moments right before being tucked in. Now Kelly Paniagua, author of the award-winning children’s book, is planning to... | Read more »
Happy Cube Death Arena Review
Happy Cube Death Arena Review By Jordan Minor on August 28th, 2014 Our Rating: :: CUBEDUniversal App - Designed for iPhone and iPad Happy Cube Death Arena is adorably violent, but very, very shallow.   | Read more »
8bit Doves, the New Game from Icebreaker...
8bit Doves, the New Game from Icebreaker Developers Nitrome, is Now Available – and in Four Colours Posted by Ellis Spice on August 28th, 2014 [ | Read more »
Ace Ferrara and the Dino Menace Review
Ace Ferrara and the Dino Menace Review By Nadia Oxford on August 28th, 2014 Our Rating: :: DINO-MYTEUniversal App - Designed for iPhone and iPad Ace Ferrara and the Dino Menace combines space combat and weird humor into a fun game... | Read more »

Price Scanner via MacPrices.net

New 21″ 1.4GHz iMac on sale again for $999, s...
Best Buy has the new 21″ 1.4GHz iMac on sale for $999.99 on their online store. Their price is $100 off MSRP. Choose free shipping or free local store pick up. Price is for online orders only, in-... Read more
Smartphone Outlook Remains Strong for 2014, U...
According to a new mobile phone forecast from the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker, more than 1.25 billion smartphones will be shipped worldwide in 2014,... Read more
Save up to $60 with Apple refurbished iPod to...
The Apple Store has Apple Certified Refurbished 5th generation iPod touches available starting at $149. Apple’s one-year warranty is included with each model, and shipping is free. Many, but not all... Read more
12-Inch MacBook Air Coming in 4Q14 or 2015 –...
Digitimes’ Aaron Lee and Joseph Tsai report that according to Taiwan-based upstream supply chain insiders, Apple plans to launch a thinner MacBook model either at year end 2014 or in 2015, and that... Read more
Sapphire Screen “Most Wanted” iPhone 6 New Fe...
According to the ‘uSell.com iPhone Most Wanted Survey’ — a representative survey of 1,000 U.S. smartphone users conducted by used iPhone marketplace uSell.com — close to half of all smartphone users... Read more
The iPad’s Real Competitive Challenger (Not S...
It’s been my contention for some time that the iPad is suffering from something of an identity crisis, and I suspect that may be a factor in slackening sales this year. Apple can’t seem to decide... Read more
13-inch 2.6GHz/256GB Retina MacBook Pro on sa...
B&H Photo has the 13″ 2.6GHz/256GB Retina MacBook Pro on sale for $1379 including free shipping plus NY sales tax only. Their price is $120 off MSRP. Read more
Life Inventory iOS Apps – Learn to Know Thyse...
James Hollender’s Life Inventory apps s are now on sale with 20% off thru Labor Day, 09/01/2014. This is a great opportunity to get started on that Moral Inventory you’ve been putting off doing for... Read more
Pocket Watch, LLC. Reveals Cloud Server For P...
Beaumont, Texas based Pocket Watch, LLC. has announced the availability of its new ActivePrint Cloud Server Powered by Raspberry Pi. With this small standalone box almost any USB printer or available... Read more
902it Simplifies Area Code Changes For Nova S...
The east coast Canadian provinces of Nova Scotia and Prince Edward Island are phasing in 10 digit telephone dialing, to be fully in place by November, in order to accommodate a second area code to... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.