Tag: programming

Z80 vs. PIC

Yesterday I wrote some lines of PIC assembly code to manage interrupt service routine so that I can select from C the code to execute when an interrupt occurs. Just to give you an idea of the pain, I will show you a comparison between a Z80 (1971) and a PIC18 (2002) in an indirect call. Let’s say that you want to jump at a program address stored in two bytes at address TL and TH.

Z80 PIC18
    jr L1
L2: ld hl,(TL)
    jp (hl)
L1: call L2

 

   bra L1
L2 movff TH,PCLATH
   movlb bank(TL)
   movf TL,W,B
   movf PCLAT
L1 rcall L2

 

Z80 routine is 9 bytes long while PIC18 spreads over 14 bytes. When it comes to execution times things are not so bad for PIC18 – 36 machine cycles compared to 53 of the Z80. My guess is that a 2002 architecture involves a pipeline that allows the CPU to crank out an instruction for machine cycle. In fact modern incarnations of the Zilog CPU have a revised architecture that runs 4 times faster or more than the original Z80.

I’ve got the PIC

It was 1971 when the first single chip CPU hit the shelves. 4004 was the name. Rough by today standards, nonetheless it featured several impressive features – among which 16 registers and 5 instructions operating at 16 bits. One year later and it was the time for 8008, with 6 registers of 8 bit each. This chip was the base for the 8080, Z80 and 8086. I am quite familiar with 8080 (basically the cpu powering the GameBoy Color) and with Z80 (the heart of many of 80s home computers – ZX Spectrum and CPC Amstrad). Later it was time for extremely elegant and rational architectures – the MC68000 and the ARM.
So I supposed that the evolution of CPUs drove to better chip with rational architecture and with legacy kludges slowly moved into the oblivion. I was happy.
Then I met the Microchip PIC. To give you an idea I would say that the PIC is to CPUs what the Cobol is to programming languages.
PIC has basically one single register, plus a set of memory location with hardwired operations. For example if you want to indirect access a memory location, you write the memory location address at a specific address, then you read another specific address and you got the indirect addressing.
PIC features an harvard architecture that is program memory is separate from data memory. Program memory can address up to 24bits, while data memory holds no more than 64kbyte, but usually you get a few kilos.
The CPU has a 31 level hardware stack for call. That means that on this stack only return addresses can be stored. If you want to use the stack to pass parameters and/or to store local variables you have to implement your software stack. In the latest PIC you get some specialized memory addresses that helps you in this task.
But obviously this architecture is not thought for modern language (if you can call modern C with his 40 years of history). So at microchip they decided that some extended instruction set was needed. I think they had best intentions and that, being engineers, they took the best decisions. But the result leave me headscraping… Basically they added a static configuration bit to the CPU. This bit is stored in the program memory, so you can’t change it without rebooting. When this bit is set the meaning of nearly half of the instruction set is altered so that rather than accessing a fixed memory address, that address is used as a displacement from a pointer half in a given memory location.
Kiss backward compatibility goodbye.
I would add that the harvard architecture doesn’t mate well with C (at least with the compiler you can buy at microchip). In fact, C language pointers may have different size according to the pointed type. But a void pointer is large enough to accommodate any size pointer. With the PIC C compiler this is not true – the size of the pointer depends of a non-standard modifier “rom” or “ram” (ram is the default). So if you point in ram the pointer is 16bits wide, but if you point in rom the pointer is 24 bits. If you move a rom pointer into a void pointer you lose the 8 most significant bits. The drawback is that you cannot write code agnostic to the location of pointed data.
Considering all, the fact that the compiler requires “main” to be declared as “void main(void)” can be well ignored.

The Web of Doom

I started programming a couple of days before yesterday, so I had several occasions of peeking a look at code written by others. According to Jeff best programmers are those who answer “mine” at the question “Which is the worst code you have ever seen?” Probably I wouldn’t qualify for the elite since I consider my code not so bad. For example, in the past days, I stumbled upon a piece of code quite crappy. Most out of curiosity I analyzed the dependency among modules. Note I am talking about real straightforward dependency, the one defined by module A calling a function in module B. I got the pretty picture you see here:

You may argue that F.c is quite independent, but the truth is that F.c is empty and not used in the project, I just included it in the graph because it was in the directory.

Now it would be just an awesome example of dependency-hell applied to programming (others may call “Big Ball of Mud”) would not be the case I have the task of adding features to this mess.

As every ball of mud of respectable dimensions, a number of anti-patterns have been consistently applied with generosity. For example, around 110 global variables have been defined in a .h file.

Ok, read that sentence again.

Variables have been defined in a header file, not just declared. This brings us to an interesting anti-pattern: each .c file has the corresponding .h file which is intended to be included only once by the .c file. I.e. F.h is the header file for F.c in the sense that just F.c has to include F.h. In this way, each header file has a section for prototypes of the module and a section for externs.

One of the most relevant members of the global community in this code is variable ‘i’. You may argue about the problem of having such a short name in such a large scope. This was my reaction until I realized that such variable was used everywhere for loop indexing. What the f*! I mean … why?! The compiler is expected to optimize away the index of a loop, possibly by moving the variable into a CPU register or by unrolling the loop. This is simply not possible when a global is involved since the compiler is not granted that someone else is using the global or it is affected by some side effect of the loop.

I tried to enter the mind of the original programmer… and I imagined a young at his (or her) first job, arriving a day at the workplace and claiming: “Yo! I had a wonderful idea! Why don’t we use a global for ‘i’ so that we don’t need to declare it everywhere!”

I won’t talk about common anti-patterns such as never-ending function body (900+ lines) or deeply nested (16 levels… a record I guess). The other aspects that stroke me are hilariously long lines and tactical comments everywhere.

80 columns per line may be a bit old-fashioned but I like it and force you to be concise and avoid too nesting, but long lines in this code easily reach 160 columns and I suppose there are some around the 200 columns.

Tactical comments are those notes left by the programmer explaining what every line is supposed to do. I am not fond of this practice that actually reduces the readability but this code reaches really unexplored worlds of tactics. Several functions have each line commented (from column 100 to column 160). If a single comment doesn’t fit in a single line (which could happen when you hit column 200) it is split along multiple lines even if the code no longer relates to the description.

Yes, I am convinced that I am not the best programmer in the world (nor one in the top ten), but I strive as I can not to write code such as this. And the reason is that a) I don’t want to lose my sanity trying to debug it (and possibly change it in the future) and b) I want everyone to live in love and peace… programmers included.

Simple I/O Messing Up

Basic I/O should be simple. I guess you agree. And I guess that’s way many C++ or Java programmers that look back to humble printf with some nostalgia. In fact it is hard to beat the conciseness and the clarity of something like:

printf("%03d", x );

When it comes to create formatted output C printf is usually one of the best tool available.
Unfortunately things are not so simple. One of the first limitations acknowledged for this little gem is that it lacks of robustness, or, put from a different perspective, it doesn’t type check.
What happens if ‘x’ in the above example is a float number? or a pointer? Or worst if the format string specifies a string pointer and an integer is passed?
This problem is mostly overcome in the GNU compiler via a custom extension that allows the compiler to check for consistency between format string and arguments.
The mechanism is enough flexible to be applied to user defined functions. Suppose you have a logging function that behaves like printf, something like

void log( LogLevel level, char const* message, ... );

That’s handy so you don’t have to perform string processing to build your message to log when you want just log. If you use Gcc and declare the function like:

void log( LogLevel level, char const* message, ... ) __attribute__((format(printf,2,3)));

Then the compiler will kindly check all the invocation of function log in your code to ensure that specifiers and arguments match.
So far so good, but enter C99. In the old days there was an integer type (int) with two available modifier (short and long). That was reflected in printf specifier/modifier: %d is for straightforward ints, %hd for shorts and %ld for longs.
And this is fine until you work on the same compiler and platform. If your code needs to be portable, then some complications are ready for you.
The last standard (C99) mandates a header, namely stdint.h, where a number of typedefs provide a wealth of integer types: grouped by size and by efficiency, you have (if I count correctly) some 30 types.
From one side this is jolly good since poses an end to the critics against C for not having an integer type with a declared bit size valid for all platforms (like Java has).
Unfortunately, on the other size printf is not able to autodetect types and thus you have to write a different format string whether your int32_t is defined as long int, or just int.
To leave the nightmare behind C99 mandates another header file – inttypes.h that provides the proper specifier for each one of those 30 integer types. For example, if you want to print an int32_t, you have to write:

printf( "here's an int32_t: %" PRId32 " and that's alln", x );

As you can see it relies on the C preprocessor that merges two consecutive strings into one.
That does the job, but, IMO some simplicity of the original idea is lost.

So long XML, welcome Json!

There was a time, some years ago, when, thanks to the then-young HTML, the markup idea with angular parenthesis was considered cool. It wasn’t infrequent to <humor> abuse it </humor> everywhere. Then, as every trend does, it went out of fashion and markup is no longer considered trendy. For bad or good we have some legacies from those days, the most notable is XML.
Xml originated from a good idea – standardize a way to describe complex data. Also Xml has a great plus, if you do everything right, you may be able to validate that an Xml description is compliant with your definition. In other words you may check if that 3d scene you are loading is really a 3d scene and not something else or something garbled up.
Beside of these good intentions I never felt at ease with Xml. First I found it very verbose, although you can write it by hand, you surely don’t want to – it’s too easy to lose some closing statement and you are likely to continuously lookup the specification to check whether that data is data or attribute.
Moreover it’s not straightforward to parse an XML file. Likely you have to employ an existing library (there are dozens for each language) and learn it.
When confronted with Xml I always thought there should be a better way to store something in a structured way. Someway it could be more readable, more writable and that doesn’t require too much brain power to write parser and interprets.
In some occasions I figured out a sort of pseudo C with braces to group values and so on.
Some time ago a coworker pointed me to json which, in fact, is a simple standard for structured data that comes from Javascript notation. Json files are easy to write and read for a human being, and writing a C parser for this format requires a couple of evenings (but if you prefer, you can use a ready made parser).
Btw, as we are in this time of the year, I wish you a Merry Christmas and Happy New Year!

Requirement baseline

I thought that by nowadays two main consensuses had been established towards requirements. The XP-ish “waste-of-time” school of thought that pretends this stuff belongs to NASA and similarly priced development and clearly are NAH (Not Applicable Here). And the “we-need-them-right” school of thought that believes in properly written and managed requirement documents.Of course, I am biased, I belong to the second school since I don’t buy the XP gibberish and I am a firmly believer that a sound methodology may not be The Solution to all software development troubles, but it is surely part of it.
So I am a bit surprised when I received a 35 pages requirements document that’s actual crap. Joel Spolsky wrote a sort of basic requirements for requirements in four parts. Well below is my list. I don’t want to compete with Joel (really, do read his post, even parts 1 and 2 and 3, it’s worth), but mine is shorter and should fit even in a tight schedule should you be requested to write specifications.
Think of it as a baseline rules of thumb:

  • start by describing the system to which the specification refers. What it does, which kind of existing systems do more or less the same.
  • don’t go ahead. These are specification, not software design. Leave out the “how”s.
  • define every acronym you are using. Not everyone knows even the most basic acronym, left out the more exotic ones (I’m still wondering what “TBP” does mean). Also define terms that are meaningful only for those who already knows what you are talking about.
  • list requirements in a way you can refer to them. Number them, or better use textual tags so that you can refer them in the same document or in the documentation that is following.
  • Don’t use the following words: “some”, “etc.”, “good”, “bad”, “fine” and the ellipses. The idea is that you have to be precise and define the entire system without leaving open holes.
  • use a spell checker. It’s easy, every modern Word Processor has it, just switch it on and fix the words underlined with the red snake (you should really do this for everything, not just the requirement document).
  • re-read everything. People is going to read and work on that document, just re-read and fix, iterate until you don’t fix anything.

As trivial as they seems, all these rules were broken at least once in the document I was handed.

Not just Chrome

The next step in Google’s march towards world domination appears to be Chrome. It is not that odd that Google aims for the web browser market, after all, they are providing web services and a tight integration with the client counterpart could just benefit their business. What is odd is that they try to enter the crowded market with a brand-new product. The most used web browser by far, at least according to the statistics is Internet Explorer which has the power of defaultness – i.e. it is the default browser on every Windows machine. Then, at a distance, Firefox is next widely used with a 16% share. Next is Safari at 3% and all the rest at 1% and below. For Chrome’s success, two factors are strongly needed – google needs to show marketing muscle and Chrome needs to be a superior product.

And this appears to be perfectly clear to Google, just have a look at the Chrome presentation.
Chrome is impressive for several things, the main reason is that it has been built from scratch. The Internet today is a very different place from what it used to be 10 years ago and architectures tailored for a simpler world may no longer suit today’s needs.

Computers as well have gone far on the roads of memory and computing power. What held as mandatory 10 years ago, may be ignored today. Take for example the “Threads are faster than processes” assumption, though still valid in principle, could be pointless on today’s hardware for most applications. Processes are safer, we know that from the dawn of computer science because different operations are insulated from each other.

Chrome will be open source. I think this is more of a need than a free decision. Today Google handles a lot of sensitive information – they have your mail, they have your documents, your photos, they know which sites you have visited, and so on. In change, you have free services, and their word they are not going to do any evil with all that knowledge about you.
A closed browser from Google would raise such privacy concerns that could seriously prevent its acceptance.

Finding the Right Path

After yesterday’s post, PaoloMan reminded me about how he and Piggi changed the CEngine pathfinding system simplifying the level design by at least an order of magnitude. In fact I had the intention of writing about their bread crumb pathfinding algorithm, but the good will got lost in some interruption of my editing. Anyway the matter is interesting and would be a pity to settle this matter with few lines embedded in another topic, so I am happy that my subattentive mind left out this yesterday.

In the beginning it was [https://www.maxpagani.org/CV-projectDesc-RS.html|Rainbow Six: Rogue Spear]. This was the first game of the studio on the then new GameBoy Advance platform with the quite ambitious goal of recreating the playing experience of the PC version of the game.
Pathfinding was needed for a number of actions of non-playing characters. Terrorists had to be able to find their way toward noises they heard, or to the last known position of their pals. Counter-terrorists had to manage to stay together following the player controller team leader.
A full A* algorithm would have been likely to be daunting on the poor ARM 7, so I devised a lighter system for all these pathfinding needs (well the idea was mine, but later I discovered it was already employed by other game engines). The idea was to define a routing network of nodes connected by straightly “walkable” rails. When a character needed to go from its actual position P to a remote position Q it queried the pathfinding system for the routing node closest to its position P. Then it asked the node for the next node in the network in order to get close to Q. In overly-simplified pseudo code it would turn out like this:

currentNode = findNodeClosestTo( P );
targetNode = findNodeClosestTo( Q );
walkTo( getNodePosition( currentNode ));
while( currentNode != targetNode )
{
    nextNode = getNextNode( currentNode, targetNode );
    walkTo( getNodePosition( nextNode ));
    currentNode = nextNode;
}
walkTo( Q );

Although the gameboy side of the algorithm was simple (even with extra code for a more realistic behaviour of characters) and fast (provided a way to quickly find the nearest node you can walk to) two non trivial problems had to be solved on the editor side.
First – networks had to be hand drawn on each map and – second – routing tables had to be computed for each node.
The reason for requiring manual work to draw networks was simply because we didn’t have enough programmer time to put the right amount of AI in the editors. One of the constraints of the project was the maximum reuse of GameBoy Color editors and tools we developed for [https://www.maxpagani.org/CV-projectDesc-RM.html|Rayman GBC] and minimally improved over the next two GBC platform games. This meant that editors didn’t understand the 3rd dimension.
So level designers had to hand draw the network taking care of connecting nodes with walkable line, trying to be very careful when more than one terrain level was involved. Also it wasn’t easy to test and debug the network. First you had to flash the game on a GBA and play it. A quick play throughout the level could not show any flaw even with a flawed network.
A properly designed routing network affected how realistic would be the movement of the characters, so networks were subject to several fine tunings.
Routing tables creation was not that hard, but the “easy way” my fellow programmers took first involved several hours of number crunching on the editor PCs. Level designers were quite mad at us for this daunting weight.
Lear produced a new and much more efficient construction algorithm, trimming down the network computation to a bunch of seconds.
But we were talking about Lara and the prophecy. Well it was clear that laying out routing networks was a big problem, luckily the AI needs for this game were quite modest. The pathfinding would have been employed for enemies to chase the playing character only after a walkable contact have been established.
PaoloMan and Piggi came out with a clever mechanism that allowed us to get rid of pathfinding networks and the related burden. The idea was to have the main character to drop virtual (and invisible on screen) breadcrumbs. When the chasing enemy loses direct sight of Lara (maybe she just turned around a corner), he can search the most recently dropped crumb for walkable way. If the most recent is not accessible, then he should go backward in time until he find a suitable one. It is like the main character defines a subset of a routing network just for the area where she is.
Talking about pseudocode, this approach would be something like:

// breadcrumb 0 is the current character position,
// 1 is the most recent and so on
breadcrumb = getBreadCrumb( Lara, 0 );
// find the most recent breadcrumb you can walk to
i=0;
while( !canWalkTo( breadcrumb ) && i < MAX_BREADCRUMB)
{
    ++i;
    breadcrumb = getBreadCrumb( Lara, i );
}
if( i==MAX_BREADCRUMB )
{
    // give up
}
// now just follows the trail
while( i >= 0 && ! canWalkTo( Lara ))
{
    walkTo( getBreadCrumb( Lara, i ));
    --i;
}
if( i > 0 )
{
    walkTo( Lara );
}

What I find notable is that, when working with games, standard solution to known problems (e.g. the A* for pathfinding) could be overwhelming or too daunting both to implement, to run and to manage. Having a clear vision of the needs of the game can point you to a proper, more efficient and simpler solution for the problem.

Free as in beer

Writing free software is like being paid for doing something you would do anyway, but without the “being paid” part.I suspect that the double meaning of the english word “free” is causing a major damage to the software industry. Although I plenty support the “free-as-in-speech” concept for the software, I am quite contrary to the “free-as-in-beer” wildly applied to every kind of software.
I consider “free-as-in-speech”, as I understand it, a sort of right of the customer – she/he is entitled (possibly for an extra) to have the source of the software you bought. That makes sense because your needs may be different from those of anyone else, and, in this way, you can customize the software to suit your needs.
You pay professionals to write an industrial strength, well polished, product, then you twiddle the ends to match your environment.
The “free-as-in-beer” is quite the opposite, you get the software for free sources and all, then, if you need, you pay someone to fix the loose ends.
From the customer point of view this is great. It would be like someone designs and builds you house for free, then you decide to keep it as is, or to pay someone to move a wall or a door.
From the software industry is a major damage at two entangled levels – money and competition. This model pushes much less money in the developers’ pockets, because customers pick free alternatives and even if they decide to pay someone for customizing them, the total money are less than what would be if everybody paid for a non-free product.
The “free-as-in-beer” has moved in the past 30 or so years, from filling empty niches for small utilities (where it could make sense) to competing against full featured applications. As Netscape teaches – you can’t compete with something given away for free.
Competition against a free product is hard, not to say, impossible. You have to compete on quality, innovation and features. And all those cost money. Though there are exceptions, free software usually tends to copy innovation from industry leaders. Quality is hard to achieve, but quality itself does not sell. What sells is “perceived quality”, i.e. the quality that the customer believes your product has. This is even harder to achieve because you have to issue focus groups, interviews, you have to work on your brand and promote it. That means a lot of money, too.
Features is another hard field, because most users exploit a few percents of all the feature-load that comes with the application. It is hard to invent something new that could appeal the customer to make a choice. New features come either from increased computing power and from research. Computing power is provided by the hardware manufactures and it is out of the developers control. Research is expensive if done in-house.
This train of thoughts brings me to the following question: “Why are we doing this?” Why programmers are happy to work for free and not, say, dentists? Ok, let’s take a less dependable example – plumbers. Why plumbers do not their job for free? I suppose that there are two reasons for this. The first is that a plumber’s work consumes materials. They need to buy and lay pipes that are not for free. A programmer does not consume any material, it is just a matter of time. Next the work of a plumber is not freely replicable, i.e. if the plumber installs a building, than he can’t copy’n’past his work on the next building.
It is all about perception – programmers are caught in a trend that is grinding music and movie industries. Among the three industries the software one is the one in the worst position, in fact the other two can count on well established labels and brands – usually you don’t consider novice singers and amateur musicians as a free alternative, a valid replacement of the work of known composers and singers.
Then there are economic interests – IBM and Sun are two of the most prominent free-as-in-beer software supporters and it has nothing to do with philanthropy. IBM and Sun business is selling hardware, usually expensive hardware and free software helps in selling more hardware because customers do not need to pay software licenses when upgrading or expanding their installed base. Google also sponsors good free-as-in-beer (but not free-as-in-speech) software because their business is advertising and free software provides the vehicle for their business.
All said, what are the chances for us programmers in the future to be paid for programming? I think there are three options – work on integration, i.e. customizing free software to suit specific user needs; work for niches where no free software exists; work for IBM, Sun or Google where people gets paid to write free-as-in-beer software.

c++0x and auto

According to the acronym C++0x, we shouldn’t be waiting for the next language standard more than one year and half. According to the uneasiness I read in the messages from the committee board, maybe the waiting could last slightly more. Anyway the next C++ is about to debut. By reading what is going to pop up in the next standard, I got the strong impression that this is another step away from the original language. Let’s face it, C++ 98 (ISO/IEC 14882:1998) is a first step away from the original, non-standard language that included templates as an afterthought. It took years for compiler vendors to reach compliance, leaving the developer community in a dangerous interregnum, a nobody’s land where portability and maintainability concerns where stronger than writing proper code. Also the standardization process left a number of lame aspects in the language – the iostream library, inconsistencies in the string class and the other containers, a mind boggling i18n support, no complete replacement for C standard library, just to name the firsts that come to mind.
The next standard seems to take a number of actions to plug the holes left in the previous one and a number of actions to define a new and different language. For example there will be a new way to declare functions, that will make appear pale an unoffensive the transition from K&R style to ANSI C. What today is declared as:

int f( char* a, int b )

is going to be declared also as:

[] f( char* a, int b ) -> int

I understand there’s a reason for this, it’s not just out of madness, nonetheless, this is going to puzzle the Joe Average developer. Once the astonishment for the new notation is expired, how is he supposed to declare functions?
The impression I got about C++0x going to be a different language has also been reinforced by a sort of backpedaling on the “implicit” stuff.
C++ has a lot of stuff going on under the hood. Good or bad, you chose, nonetheless you get by default a number of implict stuff, e.g. a set of default methods (default constructor, destructor, copy constructor and assignment operator), and a number of implicit behaviour, such as using constructors with a single argument as conversion constructor.
Now this has been considered no longer apt for the Language, so modifiers to get rid of all this implicit-ness has been introduced. E.g. conversion operators may be declared “explicit” meaning that they will not be used implicitly when an object is evaluated in a suitable context. In a class each single default method can be either disabled:

class Foo
{
    public:
        Foo() = delete;
};

Or explicitly defined as the default behaviour:

class Foo
{
    public:
        Foo() = default;
};

 

 

Again I see the rationale behind this, but I find that changing the rules of the language after 30 years of its inception is going to surprise many a developer.
One of the most welcomed addition in the new standard, at least in my humble opinion, is the new semantic for the auto keyword. If you use the STL part of the standard on a daily base, I’m quite sure you are going to agree. Let’s take for example something like:

std::vector< std::pair<bool,std::string> > bar;

After some manipulation say you want to sweep through the vector with the iterator idiom. You can wear a bit your keyboard by writing the short poem:

for( std::vector< std::pair<bool,std::string>>::iterator i=bar.begin(); i != bar.end(); ++i ) ...

 

 

I usually go for a couple of typedef so that the iterator type can be written more succinctly. The new standard allows the programmer to take a shortcut. If the type of the iterator is defined by the return type of bar.begin() then it could be catch internally and used to declare i. That turns out as:

for( auto i=bar.begin(); i != bar.end(); ++i ) ...

As you see, this is extremely more readable (and writable altogether).
Well, well, well, too bad we have to wait at least one year for the standard and an uncountable number of years before vendors update their compilers. But, if you use GNU C++ then you may not be helpless.
GNU C++ implements the typeof extension. Just like sizeof evaluates to the size of the type resulting from the expression to which it is applied, typeof evaluates to the type resulting from the expression to which it is applied. E.g.:

int i;
typeof( &i ) // evaluates to int*.

(this works much like the decltype keywords of the next C++ standard). Given that the expression to which typeof is applied is not evaluated, then no side effects could happens. And this calls for the handy preprocessor:

#define AUTO(V__,E__) typeof(E__) V__ = (E__)

Now this macro does much the yet-to-come auto keyword does:

for( AUTO(i,bar.begin()); i != bar.end(); ++i ) ...

Note that typeof doesn’t do well with the references, so, in some cases (such as the example below) could behave unexpectedly:

#include
#include

std::string foo( "abc" );

std::string const& f()
{
    return foo;
}

int main()
{
    AUTO( a, f() );
    std::string const& b = foo();
    std::cout << "a=" << a << "n";
    std::cout << "b=" << b << "n";
    foo = "cde";
    std::cout << "a=" << a << "n";
    std::cout << "b=" << b << "n";

    return 0;
}

If your compiler of choice doesn’t support typeof (or decltype), then you have to wait for it to become C++0x compliant.