Alastair’s Place

Software development, Cocoa, Objective-C, life. Stuff like that.

Named Groups in ICU Regular Expressions

Python is a pretty neat language, and one of the best things about it is its runtime library. The only real downside is that Python itself isn't really very fast, but of course you can work around this by making good use of the runtime library (much of which is implemented in C), or—if all else fails—by writing your own extension module. (This is hardly a new situation; in the 1980s many of us used to write high-performance code in assembly language so we could use it from our BASIC or even C programs; some versions of BASIC even had integrated support for assembly language… this was true, for instance of BBC BASIC on the Acorn machines, and GFA BASIC on the Atari platform.)

Anyway, one of the ways that Python programmers, like Perl and Ruby programmers, optimise their code is to make heavy use of regular expressions. The regular expression engines in these languages are fast, and it's often much quicker to match a single pre-compiled regexp than it is to write Python code to scan a string. That in mind, Python has a feature called “named capture groups”; the Python library documentation says:

(?P<name>...)

Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named 'id' in the example above can also be referenced as the numbered group 1.

For example, if the pattern is (?P<id>[a-zA-Z_]\w*), the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'), and also by name in pattern text (for example, (?P=id)) and replacement text (such as \g<id>).

(?P=name)

Matches whatever text was matched by the earlier group named name.

This is a great feature, and makes it much easier to write complicated regular expressions, since you can explicitly name the groups you want to extract and then you don't have to worry about whether or not the indices are all going to change when you add that one extra capture group that you need for whatever-it-is that you're doing.

However, and here's the problem, it's non-standard. Python supports it, but Ruby and Perl don't support it, and, as the regular expression syntax for the ICU library was derived from Perl syntax, that doesn't either.

Anyway, to cut a long story short, I want to use ICU with Python, and part of that means that I'd like regular expressions to work consistently (what I don't want is to find that my regexp matches using one or other API, but then because e.g. the Unicode character databases differ, things then break). So I've written a patch for ICU 3.4 that adds support for Python-syntax named capture groups.

Interestingly, the regexp library used by Ruby, Oniguruma, does support named groups, though with a different syntax to Python. I could have implemented that also (indeed, I think, with my patch, it can be done by just changing regexcst.txt and regenerating the associated header file), however the Oniguruma syntax looks like the kind of thing that might clash with features in future versions of Perl (it uses (?<name>...) and \k<name>, whereas Python put all of its additions inside (?P...) to avoid clashes).

Update: a new version of this patch is available.

Microprocessor Myths

In the 4th August issue of MacUser (the U.K. magazine, not its U.S. cousin), I read yet again the assertion by a journalist—Kenny Hemphill—that “The truth is, it’s many years since the PowerPC has been able to compete with Intel or AMD processorsâ€?. It really annoys me to read this. Not only is it untrue, but it’s quite unfair to the very talented engineers who worked on (and continue to work on) the PowerPC processor ranges.

The press usually support this assertion with the argument that Apple changed microprocessor because the PowerPC couldn’t keep up. Sorry guys, but this one’s just plain wrong. Apple changed microprocessor because of the various architectures’ predictions of future performance per watt. It wasn’t that the PowerPC didn’t give the right bang for your buck, but that Intel showed them technology that ran cooler at the same performance level. And when they said that (at WWDC), Apple were talking about the Core family of processors, not any previous Intel designs.

What never ceases to amaze me is the poor standard of journalism that this constant assertion about PowerPC performance actually represents. Journalists are supposed to report facts, not total speculation, but whenever they come out with this one, they are ignoring the published performance figures for machines with the various processor architectures:

ProcessorClock Freq/GHzSPECint2000SPECfp2000
PowerPC G52.717062259
PowerPC G52.515872119
Pentium 43.818632091
Pentium 43.417051561
Athlon 64 FX-572.819702261
Athlon 64 FX-532.417001634
Core Duo T26002.1617961615

According to these figures (from the SPEC website), at 2.7GHz the G5 is equivalent to a 3.4GHz Pentium 4 or a 2.4GHz Athlon 64 FX-53 for integer performance, but can keep up with a 2.8GHz Athlon 64 FX-57 or significantly outperform a 3.8GHz Pentium 4 for floating point. As for the Core Duo chip used in the new Intel Macs, well has a slightly higher integer performance than the fastest G5 chip, but the G5 comfortably outperforms it at floating point.

The point is that the G5 is certainly comparable in performance terms with all but the very latest Intel and AMD chips, and in some areas, it will outperform them. The received wisdom from the popular computing press is completely wrong.

It is true that the Core 2 Duo is substantially faster. But it’s only just been released so it’s still a gross misrepresentation to point at the Core 2 Duo and claim that the PowerPC hasn’t been as fast as Intel or AMD offerings for ages.

URL Envy

For ages I’ve been envious of many other bloggers’ set-ups, but especially the nice friendly URL schemes that a lot of other people now use. So, starting from today, my website is at alastairs-place.net, rather than the previous www.alastairs-place.net, and you can navigate the articles using the form /yyyy/mm/article_name, or get an index of all of the articles for a given month with /yyyy/mm.

For instance, this article is http://alastairs-place.net/2006/07/url_envy.


Update 2011-10-14

Actually, since I updated to Octopress, the format is now /blog/yyyy/mm/dd/article-name. There are some redirections set up to go from the old format to the new one.

"Value Added Tax" (Aka Sales Tax)

HM Revenue & Customs statistics are apparently expected to show that VAT fraud in the U.K. has reached record levels according to the BBC today.

It’s hardly surprising that when you introduce any form of system that relies on the government paying back tax that has been claimed, you’re going to get a significant amount of fraud. We’ve seen it with Gordon Brown’s silly “tax credit” system, and we continue to see it with VAT.

What I don’t get is why people think we actually need VAT. Sure, it brings in a lot of tax revenue for the government, but:

  • It places a burden on business to account for and charge VAT correctly (this is very complicated; the rulebook is well over 300 pages long, and it isn't even a complete list of all the rules that apply).
  • It artificially increases the prices of many goods, which can only be an inflationary pressure on the economy.
  • It is never adjusted. People sometimes claim that it gives the government an additional knob to twist, but it's been 17.5% here in the U.K. for as long as I can remember.
  • It disproportionately taxes the poor. Everyone has to pay VAT, no matter how much they earn.
  • It distorts the E.U.'s single market, because the rules and rates differ from member state to member state (and there are 25 different member states, all of which have complicated VAT rules like ours; what's more, they are all free to change them at various points during the year, and the penalties for non-compliance, as well as the time limits for compliance, vary from regime to regime… one or two countries even require you to employ some of their citizens in order to comply with their VAT regime!). The result is that the so-called “single market” is a joke; a hotchpotch of complicated rules administered on different terms by different states. You can even see that it isn't really a single market, since you still have to fill out CN22 forms (under a different name, but it's basically the same form) when sending goods between E.U. countries.
  • It creates difficulties for companies e.g. selling services or downloadable goods over the Internet. The E.U. insists that pretty much anything sold to its citizens should include VAT, but not everyone outside of the E.U., unsurprisingly, feels like paying tax to the European Union. Most of the large U.S. operations do, and a number of the smaller ones, but a lot simply don't care, whereas those of us within the E.U. have to do it otherwise we'll be prosecuted.
  • It creates additional opportunities for people to defraud companies (e.g. by quoting someone else's VAT number—the E.U. doesn't provide a sensible way for companies to verify that VAT numbers correspond to the identities of the people using them… you can do it, but you have to phone your local VAT administration, sit in a queue for hours on end and then read all the details out to an operator in order for them to tell you one way or another). In case you're wondering, if you quote someone else's VAT number, you may be breaking the law, but do HMRC care? No. They will pursue the company you defrauded for the VAT that you should have paid!
  • It creates additional opportunities for people to defraud the government.

There is no credible evidence that VAT is necessary or desirable. Many countries don’t have it, and their economies function perfectly well without it. We should forever curse the French, and in particular the late Maurice Lauré, for coming up with the idea.

What we should do is scrap VAT and raise the extra revenue through income taxes (in the U.K., that means Income Tax and Corporation Tax). They’re much fairer, since they’re calculated as a proportion of income, and (the daft tax-credit system aside) they offer fewer opportunities to defraud, as well as being simpler to account for.

OK, the U.K. government claims that VAT is good because it’s easy to collect (apparently), but what they really mean is that it’s easier for them.

(Note: I’m aware that VAT is collected differently from a traditional sales tax, before anyone points that out. Both types of sales tax, however, are a bad thing.)

Keyboard Confusion

Jonathon Rentzsch’s latest post about how his PowerBook/MacBook Pro’s keyboards don’t register some keypresses if both shift keys are held down was quite interesting, as was Dave Dribin’s Keyboard Matrix Help article that he linked to.

The phenomenon he’s noticed is quite normal and is due to compromises that are inevitably made when designing the layout for the keyboard’s PCBs and/or membranes. Even expensive keyswitch-based models like the Matias’ TactilePro on which I’m writing this article have their problems; mine, for instance, occasionally turns Caps-Lock on by itself when I type a sequence of keys. And if I hold down both Shift keys and try to type

QWERTYUIOP ASDFGHJKL ZXCVBNM

I get something like

WERYUIOP ASFGHKL "XCVBNM

Dave is right that you could theoretically fix most of these kinds of issues by adding diodes, though I think it’s a little unfair to suggest that their existence is entirely down to manufacturers “skimping” on a few diodes. For one thing, most modern keyboards are membrane-based, consisting of an insulating membrane with holes where they keys are, sandwiched between two membranes with conductive tracks printed on their respective surfaces. It’s quite hard to attach diodes to a rubbery membrane of that type (I don’t think it’s entirely impossible, since I’m pretty sure that there are companies out there offering the ability to attach surface mounted components to membrane circuits, but I don’t suppose it’s cheap). Two other issues that manufacturers have to consider are assembly costs (remember—you don’t have to place components on the matrix at all if there aren’t any, which saves an entire assembly step) and the physical geometry of the innards of the keyboard… obviously you can’t put diodes in spaces that are too small for them.

Also, the keyboard matrix designs in modern keyboards are usually pretty good

SQLite and Mac OS X

SQLite is quite a popular library, particularly on Mac OS X where it’s actually used to implement some system features.

Unfortunately, some of the filesystems on OS X (AFP, for instance) don’t implement advisory locking via the POSIX function fcntl(), which leads SQLite to report that the “database is locked” whenever you try to use it.

Now, SQLite is included with Mac OS X, and Apple have been kind enough to solve this problem for the version that they provide (3.1.3). Unfortunately, that version doesn’t support some of the syntax that gets generated by newer versions of SQLAlchemy, which I’ve been evaluating as part of a new design for my company’s website. So I needed to upgrade to a newer version to make it work, and since my home area is on an AFP share, I needed it to work on that.

The upshot is that I’ve ported Apple’s fix from 3.1.3 to the latest version of SQLite (3.3.6). Here’s a patch. To apply it, download the patch and the sqlite 3.3.6 sources (1.59MB). Then, in Terminal, do something like the following:

alastair$ tar xvzf ~/Desktop/sqlite-3.3.6.tar.gz
sqlite-3.3.6/
sqlite-3.3.6/art/
sqlite-3.3.6/art/tmp/
...
sqlite-3.3.6/publish.sh
alastair$ cd sqlite-3.3.6
alastair$ patch -p1 < ~/Desktop/sqlite-3.3.6-osx.patch

Then build it as normal. Note that if you run make test on an AFP volume, you’ll spot that one or two of the tests will fail. I think this is because of the differences in semantics between POSIX and AFP byte-range locks. If you run them from a local volume instead, they succeed as expected.

If you want the new build to match the version supplied by Apple, remember to configure it with --enable-threadsafe and --enable-tcl to turn on thread-safety and Tcl support.


Update 2011-10-14

I’ve removed this patch, as Apple has long since updated SQLite to a newer version.

Myopic View?

John Gruber’s Mac OS X Tipping Point article remarks that

The myopic view of the classic Mac OS held by OS X era switchers, I suspect, stems from a thought process that runs like this: I wasn’t using a Mac in the late 90s, and I care about computers, and a bunch of my friends and colleagues feel the same way, so therefore no one who cares about computers was using a Mac in the late ’90s.

As a member of the group of “OS X era switchers”, I think this is manifestly unfair. It is a gross generalisation, and fails to take account of a number of factors affecting people like me. For instance, in the late ’90s, I would have loved to have been using a Mac. As someone who previously used Atari ST machines through the late ’80s and early ’90s, the Mac was a case of a familiar (but slightly better) user interface, familiar (but slightly better) hardware and generally better (but more expensive) software. There are, of course, exceptions—anyone familiar with the latter days of the Atari ST range will remember remarks in the press about the number of Calamus DTP users decrying the lack of functionality in Quark Xpress, and many of the high-end music packages that today are run on the Mac and PC platforms originated on the ST platform.

However, as a student without a proper income, I wasn’t able to afford the new PowerPC Macs, and didn’t see much of a future for the admittedly attractive 68040-based machines that were still on sale. Nor were the clone machines particularly competitively priced (indeed, had I bought one of those, I would probably have regretted it, since they had the price point of Apple’s hardware but without any of the finesse).

So I was forced into the world of the PC and thereby Windows. And let me tell you, it is pretty horrible having to switch from an operating system that has a Mac-like UI with a mix of UNX and DOS-like underpinnings (in the latter days drifting ever closer to being UNX-like) to the frankly ropey UI of Microsoft Windows. Not that the Mac UI was perfect, but it was a lot better than Windows. I actually think that the Mac UI has got a bit worse, rather than better, with the introduction of OS X, but I’m hoping that Leopard will go some way towards resolving that.

You may ask why didn’t I then buy a Mac for ages after that? Well, although my income had increased somewhat, I had an investment in PC software at that point. The thing that originally tempted me into the world of the Mac was the fact that the titanium PowerBook was the best UN*X-based portable available. I wasn’t necessarily expecting to shift completely to the Mac, but when I found it so much less annoying to use than my PC, that’s what happened. And now, my business is based around the Mac too.

Ironically, perhaps, given that the ST was moving towards a model with a UN*X-like base and a Mac-like UI, modern Mac OS X has done exactly that! Though there are still a few things, to my mind, that Apple could have usefully learned from buying an old ST and looking at the software on it. For instance, being able to use windows that are not on the top, or the way that dragging a file from one window to another has the same meaning wherever the file is coming from or going to (on the ST, this would always copy the file… to move it instead, you had to hold a key; the Mac, like Windows, uses a ridiculous heuristic based on whether the file is on the same disk, forcing you—unnecessarily—to watch for UI cues that tell you what you’re going to do and modify your behaviour accordingly). Tear-off menus are quite handy too, as is a send-to-back button on the windows and the ability to resize from any side or corner. (I am aware, before anyone points out, that the original GEM didn’t have many of these features… but later GEM replacements, including Geneva, MagiC, nAES et al., certainly did/do).

Phone Home Hysteria

It’s interesting to read Daniel Jalkut and Jonathan Rentzsch’s opinions of Apple’s new Dashboard auto-update mechanism.

What really annoys me about this particular issue is the sort of government-is-out-to-get-me, tinfoil-hat kind of hysteria that seems to affect both the press and many commentators on the Internet.

Let’s step back for a moment and consider.

Who is "out to get me"?

Well, it certainly isn’t the corporations.

Legitimate business does have an interest in sending marketing information to you, but it also realises that you won’t buy from people who persistently pester you. It is certainly true that the previous trade in personal details between marketing organisations has resulted in a backlash, notably including the creation of new laws in Europe and indeed other parts of the world. But, to re-iterate, legitimate business has nothing to gain from harming its customers.

However, the current darlings of popular culture, the P2P providers, along with their cousins in the cracking community (who write tools to help people steal software), are not legitimate. They will quite happily steal your information, since they’re already breaking the law —or, in the case of the P2P software developers, assisting you to break the law (however much they may disclaim such responsibility, there is not a P2P software developer alive who doesn’t know that the primary purpose of their products is to allow the general public to steal music, software and films without paying the copyright holders; their marketing on the Internet makes this pretty obvious, frankly).

The other group of people who are out to get you are those who steal personal information for profit, such as identity thieves, confidence tricksters, black-hat hackers and the like. They are very different from legitimate corporations.

What about the Sony “root-kit”?

Well what about it? What were Sony trying to achieve with their DRM-enabled CDs? The answer is that they were trying to stop the general public from stealing their artists’ music and distributing it over the P2P networks. Sure, what they did prevented some legitimate “fair use”, but they are entitled to be paid for material for which they own the copyright, and if the public are sticking their collective finger up to them in droves, they must protect the interests of their shareholders and their signed artists.

I don’t like DRM’d CDs particularly, and I don’t approve of surreptitiously installing software on users’ machines either, but, if they (probably rightly) concluded that what the RIAA is doing won’t work, and that the governments of the world aren’t really that interested in helping, what do you expect them to do? Tell their staff that they won’t be getting paid this month because that new album that just came out was distributed everywhere by P2P and as a result made a massive loss? Yeah, right, that’s fair.

If you, like me, think they did the wrong thing, that’s great. But most of us are lucky enough to live in democratic countries. If you accept that copyright isn’t working, tell your representative what you think should be done to fix it. Otherwise, someone (whether your government, or Sony, or some other party) will impose a solution that you don’t like, or (worse), the problem won’t get solved and there will be less music, less software and fewer films. Equally in a democracy, you should abide by the law; if you don’t like it, tell your representative, don’t go breaking it. The point of democracy is that we all get a vote and that rules are made on the basis of the opinion of the majority; sometimes you get your way, sometimes you don’t, but you have to accept that for the good of us all.

But I want to know what data is being sent and where

OK, so ask. Legitimate organisations have nothing to fear from telling you, and indeed in some parts of the world, they must tell you if they use some pieces of information about you.

How do I know that (for instance) Apple or Microsoft aren't "out to get me"?

Legitimate businesses comply with the law, in all sorts of different ways. Even when things do go wrong, they tend to be problems relating to the finances of the business (as in the case of Enron, for instance) and are often driven by the fear of the Directors who, like habitual gamblers, find themselves in a mess but think they can trade their way out of it. Corporations very rarely wilfully break the law, though they sometimes do so accidentally. Wilful lawbreaking is certainly much less common amongst corporations than it is amongst individuals, partly because of the consequences that such activity can have in the long run.

Legitimate businesses are regularly audited, for all sorts of reasons. Shareholders may insist on audits to make sure the Directors are not up to no good. Directors may insist on audits to make sure that business processes are functioning as intended. Audits may be held for statutory reasons. Audits may also be held for reasons associated with particular certifications held by the business (e.g. ISO9000).

Legitimate businesses want to retain you as a customer. Unless you are especially obnoxious, a legitimate business will do its best to keep the relationship sweet. This is why when you buy a software package, you are typically offered free support, or discounts on upgrades to future versions. It isn’t just the business “being nice”—they want future business from you. It isn’t in their interests to steal your data and do something unpleasant with it; if they were found out, they’d stand to lose a lot more than they would ever gain (unlike those operating illegally or on the verge of illegality, who are already sticking two fingers up to the law and are more interested in taking your money quickly so they can get away with it).

But they're watching my every move!

No, they aren’t. The vast majority if supposed intrusions on your privacy are actually cases where something is processed by an automated system and immediately thrown away. The reason for this is simple; storing the volumes of information that such things can collect is impractical for even the largest of organisations. Very often it’s uninteresting as well.

For instance, if you have the iTunes Mini Store turned on, it tells a computer at Apple what you’re listening to at the moment so that the Mini Store can suggest other things you might like (a useful service, actually, when you stop to think about it). Consider what information this provides to the machine(s) running the Mini Store service; obviously, there’s the name of the song you’re listening to… then there’s your IP address, the time, the date, the time zone, the name of the album, the name of the artist, and maybe other things too. Now consider that iTunes is reported to have over 18 million users. Assume that each of these listens to two songs a day and that they all have iTunes Mini Store enabled (as was originally the case when the feature was added). Then let’s suppose that the average size of the data sent to the mini store is 128 bytes (and that’s optimistic). That works out at over 1.5 terabytes of data per year. Doable, certainly, but expensive. Do you really think Apple want the information enough to set up and maintain a database that grows at that rate? I don’t.

Sure, at some point in the future, this kind of thing might be feasible, but let’s also think about what a legitimate businesses are really going to be interested in. They don’t care if you cross-dress at weekends, if you’re having an affair, if you spend your spare time surfing for porn, swinging or messing about with prostitutes. They don’t care if you’re racist or rude, if you’re a neo-con or a communist, if you’re gay or straight. Equally, they don’t care if you’re a vicar who spends his time nibbling cucumber sandwiches and listening to Mozart. They don’t care, to put it bluntly, what you do with your spare time. As long as you don’t steal their products or upset their staff, as far as businesses are concerned, what you do is between you and whatever god you believe in.

There are exceptions. Most businesses would be happy to report you if they think you’re breaking the law, e.g. if they catch you with pedophile images or plans to blow up the London underground. In some cases, the law actually requires them to do so, but then most people would want them to. And obviously, they want your business; so maybe if you buy products from their competitors rather than them, or if you’re obviously part of their target market, they’ll be interested—but that’s a very focussed sort of interest, and frankly one that we should all encourage because it’s competition that drives prices down and quality up.

But I don't trust “Them”

Many corporations, particularly the larger ones, are publicly listed. That means you can buy shares in them. You can own them!

As a shareholder, you are responsible for appointing the Directors of the company. For instance, if Apple’s shareholders wanted, they could rid themselves of Steve Jobs and appoint someone else in his place. Obviously such actions are subject to a democratic vote based on the amount of money each shareholder is risking. Own more shares, and you get more votes. But that doesn’t stop shareholders from banding together.

Do you really think that a corporation is going to deliberately do something that would upset the people who own it? The people for whom the corporation is run, to make a profit? The people who can vote out the Directors at a drop of a hat. The people who can refuse to ratify the Directors’ pay, who could insist on endless audits, refuse to agree the accounts (which can, in extreme cases, result in the Directors being prosecuted and disqualified from holding such a post for some time) or even shut the company down completely?

Does that make sense to you?!

OK, some companies aren’t publicly listed, and in many publicly listed companies your individual voice is going to be small (though the opinions of e.g. pension funds, who represent many members of the general public can still be crucial to the running of the business). But most privately owned companies aspire to going public, with the huge increase in the value of their shares (and consequent increases in the wealth of their owners) that that implies. If you were going to do that, do you suppose that it makes sense to upset potential future shareholders?

Put simply, think of the effect on companies’ stock prices, and also the problems that it could create for them if they end up facing a shareholder revolt.

So why the fuss about privacy?

It is true, as I mentioned above, that some marketing organisations were selling customers details to other marketing organisations without mentioning it to or asking their customers first. This is definitely not the kind of thing that customers expect, and quite rightly there has been a backlash against this sort of thing, the result of which is that many countries have passed laws governing the trading of customers’ details.

But there’s still an enormous gulf between this and the sort of things that consumers should really be worried about (identity theft, blackmail, confidence tricksters, spammers and the like). Apple and Microsoft won’t be stealing your identity, blackmailing you, trying to scam you, or sending you dodgy e-mails about children and animals any time soon.

I've read 1984. And I am not a number!

Great (no, really, it is). Just don’t get all paranoid about it. 1984 is fiction, and whilst some things from the book do have echoes in today’s society, you need to think very carefully before assigning the sinister motives of “Big Brother” to organisations simply because they seem to you to be large and powerful.

Nor should you blindly believe what the media has to say on the matter. Stories are often exaggerated or just plain mis-reported. It’s much more fun for the media to report sensational headlines, even when—as often turns out to be the case, if you look deeper—the reality is much more mundane.

So what should I do?

Chill out. Don’t foam at the mouth when you find a new automatic update mechanism that nobody told you about, or when you discover that some new feature happens to work via (shock horror) a server somewhere that has the potential to collate the data somehow. The real world is much less sinister than the make-believe world that some of the more rabid privacy advocates think they inhabit.

Too Hot…

I’m too hot. And yes, I’m going to whinge about it to you :-)

It’s currently at least 25°C (air temperature) in this room (the thermometer I just fetched is still heading slowly upwards), and the Met Office people on the TV said this morning that it was going to be over 70% humidity. The air surrounding me feels like it’s probably gone over 90%, but then I’m a sweaty customer in this sort of heat so that’s hardly an objective assessment of the situation :-)

Of course, people in some parts of the world will look at this post and think “Hey, that’s a pleasantly cool day, what’s this guy talking about?”. Equally, in temperatures I feel more comfortable in, they might don ski-wear when I was still wandering about in jeans and a T-shirt. Funny how even peoples’ impressions of temperature are relative.

Writing the '*' in the Wrong Place (a.k.a. Bjarne Stroustrup, you Are Wrong!)

For some time now, it’s bothered me that a lot of people are being taught to write

int* a;

rather than

int *a;

The problem, as any experienced C programmer should be able to tell you, comes when you write

int* a, b;

Unfortunately, the interpretation implied by the spacing is that a and b are both pointers to integers. This is not, however, the case; instead, a is a pointer to an int, whilst b is an int.

The way the compiler reads this declaration mirrors the way that C programmers tend to write these kinds of statements:

int *a, b;

where it is obvious from the spacing that *a is an int (which implies that a is a pointer to an int) and b is an int.

The point is that the green part is the type, whilst the things you are declaring are the blue parts. The type of the resulting variable a is certainly pointer-to-int, but the declaration to the C compiler does not say that, it just says that *a is an int, and to get the type of a, you have to read outwards from the variable name. This way of reading declarations works for all C and C++ declarations. The other way does not, forcing people to treat declarations like “int* a” as a special case.

Writing things in such a way that a human being will read them differently to the compiler is just plain wrong. You can’t (as Bjarne Stroustrup tries to) justify it by saying that people shouldn’t write multiple variable declarations on a line—the C syntax (like that of C++) is perfectly clear and very easy to understand, provided you don’t try to space it as if it was e.g. Pascal.

It’s particularly telling that you can (if you like) write declarations using additional parentheses, like this:

int (*a);
int b, (*c), d;

though you can’t write

(int*) a;

(Well, not as a declaration, anyway…)

Of course, this syntax isn’t normally used by macho parenthesis-hating C programmers :-)

Anyway, consider this a plea, particularly to teachers of C and C++ programming: Please don’t teach your students to write ‘int* a’. It isn’t how the compiler reads it, and you will only make things more confusing for them.

Finally, for those people who like a puzzle, here’s an interesting declaration to decipher:

int (*(*fn)(const char *n))(int a, int b);

and you can award yourself extra brownie points for knowing—without using typedef or any pre-processor macros—how to write a function definition, a pointer to which could be assigned to a variable like the one above.

(Hint: think where you’re supposed to start reading the declaration to work out the type of fn.)