Sunday, February 22, 2009

Things I Didn't Know about C++: Local Classes

C++ is a complex language, and although I thought I knew it pretty well, I'm continuing to find areas of the language that I either didn't know or didn't understand well enough. So, on the (possibly narcissistic) assumption that others may not know enough about them too, here's a brief series of postings about them.

First up are local classes, which are not the same thing as nested classes.

class imitation_string {
public:
  // This is a nested class.  Other code can then use imitation_string::iterator.
  class iterator {
  public:
    iterator& operator++();
    iterator& operator--();
    char& operator*();
  };
};

void string_tokenizer(const imitation_string& in, std::vector<imitation_string>& out)
{
  // This is a local class.  It can only be used from within this function.
  class token {
    // Insert class definition...
  };
}

Local classes are closely related to nested (local) functions, which are not permitted in C++.

// Not valid C++.
int f()
{
  int i = 0;
  void g()
  {
    // A nested function has access to its enclosing function's variables.
    i++;
  }
  g();
  return i;
}

The position of local classes within the design of C++ seems very awkward to me. "True" nested functions require special implementation from the compiler, due to the requirement that they be able to access their enclosing functions' stack frames, and calling a nested function (via a function pointer) after its enclosing function has exited is a quick way to crash a program. This might be reason enough to omit them from the C++ language, but it didn't stop the GNU C Compiler from implementing them as an extension. Stroustrup dismisses local functions by saying that "most often, the use of a local function is a sign that a function is too large," but that didn't stop local classes from being permitted (with the same "too large" caveat). Nested functions occupy a much more comfortable position in other languages; Pascal (and therefore Object Pascal and Delphi) have supported them for ages, they're a key development technique in Javascript (used for everything from closures to jQuery event handlers), lambda expressions offer equivalent functionality in languages which support them, and so on.

Even ignoring their awkward position, local classes in C++ have some odd traits. First, they can neither be used as template parameters (so no smart pointers to local classes). Local class templates and local template methods are likewise prohibited. Second, although local class methods cannot access the enclosing function's variables (unlike a nested function), they can access static local variables within the enclosing function.

// Valid C++!
int f()
{
  static int i;
  class g {
  public:
    static void Execute() { i++; }
  };
  g::Execute();
  return i;
}

Similarly, local classes within a class method can access static members (even protected and private static members) of the enclosing class, and such access is implicitly scoped. They can also access protected and private members of friends of the enclosing class.

class F {
public:
  DoStuff();
private:
  static int i;
};

int F::DoStuff()
{
  class G {
  public:
    static void Execute() { i++; }
  };
  return i;
}

Various workarounds have been proposed for local classes' inability to access local variables of their enclosing functions. Herb Sutter gives a rundown of the various options in GotW #58. His final solution is worth mention; in an bit of C++ judo, he turns the enclosing function into a class, whose constructor contains the function body and which is implicitly convertible to the desired return value. The function's local variables become member variables, and the local functions / nested classes become class methods that can access these member variables.

Local classes have two main uses. First, they can be used to augment the regular control flow of a function. For example, Boost's new ScopeExit library lets you write arbitrary code to be executed whenever a code block exits (whether it exits by finishing, an explicit return statement, or throwing an exception). It implements this by defining a local class whose destructor executes the code RAII-fashion. The Google C++ Testing Framework offers another example of augmenting control flow with local classes. A unit testing framework needs both a way to abort the current test if a test assertion fails and (ideally) a way to signify that certain failed assertions are expected. The standard way to do this is to have failed assertions handled by throwing exceptions, and expected failures can be caught and handled. However, a design goal of Google Test is to avoid requiring the use of exceptions for maximum portability. Failed assertions are handled by a simple return statement. Expected assertions are wrapped in a local class method so that the return statement doesn't abort the entire function.

static int i = 1;
// This asserion:
ASSERT_EQ(1, i);
// expands to code vaguely resembling this:
if (1 != i) {
  ReportFailedAssertion(1, i, "ASSERT_EQ(1, i)", __LINE__);
  return;
}

// This assertion:
EXPECT_FATAL_FAILURE(ASSERT_EQ(2, i));
// expands to code vaguely resembling this.  Note the local class scoped to
// a dummy do/while block.
do {
  class GTestExpectFatalFailureHelper {
  public:
    static void Execute() {
      if (2 != i) {
        ReportFailedAssertion(2, i, "ASSERT_EQ(2, i)", __LINE__);
        return;
      }
    }
  };
  GTestExpectFatailFailureHelper::Execute();
} while(false);

Second, local classes can be used like any other class or function, as a mechanism for reusing and refactoring code. If you have code that appears in more than one place within a function, but is too specific to be used outside of that function, then following the principles of information hiding (if you prefer the dry CS term) or Spartan programming (if you prefer classical historical allusions or gratuitous Frank Miller references), you can use a local class to keep the code scoped as narrowly as possible. Personally, I've very rarely found code that's repeated within a function but is so specific that it will never be used outside of that function. However, this could simply be a case of my available tools determining how I solve problems. For example, Delphi permits local functions, and Delphi developers seem to find them moderately useful; the latest incarnation of Delphi's Visual Components Library, consisting of roughly 11,000 methods across 220,000 lines of code, uses about 190 local functions. Walter Bright, the creator of the D programming language, gives several examples of how nested functions can be used. He concludes,

Lack of nested functions is a significant deficit in the expressive power of C and C++, necessitating lengthy and error-prone workarounds. Nested functions are applicable to a wide variety of common programming situations, providing a symbolic, pointer-free, and type-safe solution.

They could be added to C and C++, but to my knowledge they are not being considered for inclusion. Nested functions and delegates are available now with D. As I get used to them, I find more and more uses for them in my own code and find it increasingly difficult to do without them in C++.

Sunday, February 15, 2009

The Problem with the Web

In "Why Chrome is Shiny," Jonathan Edwards does a wonderful job of articulating the vague misgivings that I've had about the current rush of interest in web applications:

I have realized that Internet browsers are a dead end, much like MS-DOS was... Some examples of these problems:

  1. No multithreading
  2. Reference counting GC, causing memory leaks
  3. Only 2 outgoing TCP sockets, and only to same site as URL
  4. Whole-page rendering, making dynamic layout changes unpleasant
  5. DOM incompatibilities
  6. Event firing and handling incompatibilities
  7. Limited standard libraries, and poor support for large-scale programming

All of this reminds me very much of MS-DOS. Like the browser, it was essentially a toy that was not originally intended to be used for anything serious or intense. Hackers came in and discovered they could do all sorts of things beyond those original intentions, and that they could get rich in the process. In the resulting gold rush there was no time to worry about fixing the platform. MS-DOS willfully ignored the existing body of knowledge about how to design an operating system.

Javascript has its good parts - prototypes, first-class functions, JSON - but it has plenty of problems too. People are expending prodigious effort finding solutions or workarounds for those problems - for example, the V8 and TraceMonkey teams' efforts to improve Javascript's performance - but I can't help but wonder if that effort would be better spent on a language that was, you know, designed for the purpose for which it's being used.

And Javascript is only one problematic aspect of current web development. Web security, for example, is awful; Jeremiah Grossman estimates that 90% of sites have vulnerabilities, and he and his team can generally find a vulnerability in under two minutes. (And he writes some great war stories about doing so.) Security for web development is roughly where security for network server development was twenty years ago: it's possible to write secure code, but only if you know what you're doing, and only if you never make a mistake. Twenty years ago, that meant never overflowing a buffer, never using sprintf/strcpy/strcat, and being very careful how you used the nonintuitive strncpy/strncat. Now, it means never building an SQL query from user data, always HTML-escaping text before outputting it, blocking CSRF, and so on. Development on the desktop and in network services is finally advancing from "secure if you try really hard" to "secure by default", thanks to training and awareness efforts by SANS and others, more secure (harder to misuse) C libraries such as Microsoft's and OpenBSD's, the selective replacement of C and C++ with higher-level languages that eliminate the possibility of memory allocation or buffer overrun errors, and vendors (primarily Microsoft) finally embracing the principle of least privilege. Web development has yet to make this transition from "secure if you try hard" to "secure by default." (Unless there have been advances that I'm not aware of? The most intriguing idea I've read is to use a strong type system, such as Haskell's, to distinguish between unsanitized and sanitized data.)

In spite of all of the problems with web development, it's the best (only?) method we've found of writing cross-platform, zero-deployment, sandboxed apps that can share data where needed and access data from anywhere. These are valuable features.

What should be done about the problems with web development? Silverlight might have the right idea, but I prefer my web without vendor lock-in. One approach (apparently favored by Edwards in "Why Chrome is Shiny") is to use a platform like the Google Web Toolkit or haXe to build on top of the current web platform and (hopefully) hide many of its shortcomings. At the very least, I figure we should be aware of the problems of the current technology craze and be a bit cautious of jumping on the bandwagon. That's good advice for technology in general.

Edit: I don't feel like I communicated very well... What seems strange about much of web development - what seems surreal about so much of software development in general - is that none of it has to be this way. It's not like other fields of engineering where are solutions are constrained by the laws of physics or by the chemical properties of the substances we're working with or similar; it's all, as Fred Brooks says, "castles in the air, [built] from air." It's largely an accident of history and of market forces that this combination of HTML and CSS (incompatible between vendors and often done improperly on web sites), Javascript (rushed out the door by Netscape and saddled with some bad design decisions), and XHR. And now, developers have spent prodigious effort making this concoction work, and with so much brains and sweat put into it, it often works amazingly well. But it's a place no one would choose to start from if they could have a choice.

Friday, January 30, 2009

Floods, Recessions, and Other Forces

I found out today that a friend of mine was getting laid off.

I make computers obey me for a living.  I consistently try to improve my skills, and I'd like to think that I'm pretty good at what I do.  I tend to assume that I can master any problem or challenge that comes my way.  But today was a reminder that there's still a great deal that I can't control.  Professionally, I can't control my boss, my coworkers, vendors, or customers; in the broader realm of life, I can control even less.

As Dennis Bakke said in Joy at Work, when there's a hundred-year record flood, it doesn't matter how well your house is built.

It was an important reminder.

Wednesday, January 28, 2009

A Simple Essay

Like many developers, I sometimes over-complicate my code, whether in an attempt to generalize and future-proof it or to just test out some new technique. In theory I know that over-complication is bad, but trying to do this in practice raises questions that I don't know how to answer. So, following a time-honored blogging tradition, I'm going to provide quotes from better known, more insightful people who address the topic, and I'll intersperse a few thoughts of my own so that I can act like I'm adding something to the discussion. (Each of the linked articles and papers is recommended reading for more treatment of this topic.)

“Controlling complexity is the essence of computer programming.” - Brian W. Kernighan (source unknown)
“Complexity is the business we are in, and complexity is what limits us.” - Frederick P. Brooks, The Mythical Man-Month, chapter 17

The main reason for pursuing simplicity is our own limitations:

“Programming is a desperate losing battle against the unconquerable complexity of code, and the treachery of requirements... A lesson I have learned the hard way is that we aren’t smart enough... The human mind can not grasp the complexity of a moderately sized program, much less the monster systems we build today. This is a bitter pill to swallow, because programming attracts and rewards the intelligent, and its culture encourages intellectual arrogance. I find it immensely helpful to work on the assumption that I am too stupid to get things right. This leads me to conservatively use what has already been shown to work, to cautiously test out new ideas before committing to them, and above all to prize simplicity.” - Jonathan Edwards, “Beautiful Code”

Edsger Dijkstra made a similar point over thirty-five years ago:

"The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague." - Edsger W. Dijkstra, "The Humble Programmer"

Part of Djikstra's remedy, as I understand it, was to push for radical simplicity in programming languages, on the belief we must be able to easily and entirely understand “our basic tools.” The trend has instead been to push more and more complexity into our tools in hopes that it will make our applications manageably simple: languages continue to sprout new features, optimizing compilers rearrange our functions and variables behind our backs, garbage collection makes resource reclamation non-deterministic, and environments like the JVM and CLI become massive projects in their own right.

Accommodating human frailty is the philosophical reason for simplicity, but there are practical benefits as well:

“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?” - Brian W. Kernighan and P. J. Plauger, The Elements of Programming Style, p. 10.

(A well-known quote, but have debugging advancements like IDE integration, VM playback, and omniscient debugging and techniques like TDD changed this?)

One reason for [Extreme Programming's encouragement of simplicity] is economic. If I have to do any work that's only used for a feature that's needed tomorrow, that means I lose effort from features that need to be done for this iteration... This economic disincentive is compounded by the chance that we may not get it right. However certain we may be about how this function works, we can still get it wrong - especially since we don't have detailed requirements yet. Working on the wrong solution early is even more wasteful than working on the right solution early. And the XPerts generally believe that we are much more likely to be wrong than right (and I agree with that sentiment.) The second reason for simple design is that a complex design is more difficult to understand than a simple design. Therefore any modification of the system is made harder by added complexity. This adds a cost during the period between when the more complicated design was added and when it was needed.” - Martin Fowler, “Is Design Dead?”

Although simplicity has many benefits, complexity is often unavoidable:

“The complexity of software is an essential property, not an accidental one. Hence descriptions of a software entity that abstract away its complexity often abstract away its essence. Mathematics and the physical sciences made great strides for three centuries by constructing simplified models of complex phenomena, deriving properties from the models, and verifying those properties experimentally. This worked because the complexities ignored in the models were not the essential properties of the phenomena. It does not work when the complexities are the essence.” - Frederick P. Brooks, “No Silver Bullet: Essence and Accident in Software Engineering” (as printed in The Mythical Man-Month)

Brooks gives other reasons for complexity being an essential property of software: communication, the number of possible states, and interdependencies all scale nonlinearly, and unlike other human constructs, no two parts of a program are identical.

“I find languages that support just one programming paradigm constraining. They buy their simplicity (whether real or imagined) by putting programmers into an intellectual straitjacket or by pushing complexity from the language into the applications.” - Bjarne Stroustrup, “The Real Stroustrup Interview”

This is one of the few “pro-complexity” quotes I've been able to find. Stroustrup is arguably biased, considering the complexity of his most famous creation, but his point is valid: some complexity is unavoidable and sometimes the best you can do is to push it to the language or the libraries so that the applications can (hopefully) avoid dealing with it. This is why I think that, e.g., the Boost libraries are a good thing, despite or because of their complexity.

Complexity is a major risk to software projects.

“What is the most common mistake on C++ and OO projects? Unnecessary complexity – the plague of OO technology. Complexity, like risk, is a fact of life that can't be avoided. Some software systems have to be complex because the business processes they represent are complex. But unfortunately many intermediate developers try to “make things better” by adding generalization and flexibility that no one has asked for or will ever need. The customer wants a cup of tea, and the developers build a system that can boil the ocean [thanks to John Vlissides for this quip].” - Marshall Cline et al., C++ FAQs, Second Edition, p. 36
“What's the Software Peter Principle”? The Software Peter Principle is in operation when unwise developers “improve” and “generalize” the software until they themselves can no longer understand it, then the project slowly dies.” - Marshall Cline et al., C++ FAQs, Second Edition, p. 37

The term “Software Peter Principle” was coined in C++ FAQs, but it's at least spread enough to get its own Wikipedia page with some added discussion. “Avoid Death by Complexity,” by Alan Keefer, covers the same subject matter and is too long to quote here; just go read it.

Development methodologies can help in the pursuit of simplicity:

I suggest: Exploiting the mass market to avoid constructing what can be bought. Using rapid prototyping as part of a planned iteration in establishing software requirements. Growing software organically, adding more and more function to systems as they are run, used, and tested. Identifying and developing the great conceptual designers of the rising generation. - Frederick P. Brooks, “No Silver Bullet”

Popular perception often views “No Silver Bullet” and The Mythical Man-Month as pessimistic, but Brooks argued that the essential complexity could be steadily reduced; his approach of rapid prototyping and iterative organic growth anticipates some the agile development techniques.

“Do the simplest thing that could possibly work.” “You Aren't Gonna Need It.” - Extreme Programming maxims.

Keep in mind, though, that XP practices reinforce each other; YAGNI and “do the simplest thing” won't work unless you're also practicing unit tests (to find out if your simplest thing actually does work, and to permit refactoring) and refactoring (to keep your design clean as your “simplest” and “not needed” code necessarily grows).

As I try to figure out the balance between simplicity and complexity, I was encouraged to read that someone as experienced as Martin Fowler seems to struggle with some of the same questions:

“So we want our code to be as simple as possible. That doesn't sound like that's too hard to argue for, after all who wants to be complicated? But of course this begs the question "what is simple?" ... [One major criteria for XP is] clarity of code. XP places a high value on code that is easily read. In XP "clever code" is a term of abuse. But some people's intention revealing code is another's cleverness... In his XP 2000 paper, Josh Kerievsky points out a good example of this. He looks at possibly the most public XP code of all - JUnit. JUnit uses decorators to add optional functionality to test cases, such things as concurrency synchronization and batch set up code. By separating out this code into decorators it allows the general code to be clearer than it otherwise would be. But you have to ask yourself if the resulting code is really simple... So might we conclude that JUnit's design is simpler for experienced designers but more complicated for less experienced people?...Simplicity is still a complicated thing to find. Recently I was involved in doing something that may well be over-designed. It got refactored and some of the flexibility was removed. But as one of the developers said "it's easier to refactor over-design than it is to refactor no design." It's best to be a little simpler than you need to be, but it isn't a disaster to be a little more complex. The best advice I heard on all this came from Uncle Bob (Robert Martin). His advice was not to get too hung up about what the simplest design is. After all you can, should, and will refactor it later. In the end the willingness to refactor is much more important than knowing what the simplest thing is right away.” - Martin Fowler, “Is Design Dead?”

Of course, this struggle between simplicity and complexity is hardly new with or specific to programming.

'Tis the gift to be simple, 'tis the gift to be free...” - Joseph Brackett Jr., “Simple Gifts,” 1848

Saturday, January 17, 2009

No Boost for Google

I recently came across the Google C++ Style Guide, and since the folks at Google are geniuses, I thought it would be worth a read. Among the various sound practices, sage advice, and sensible conventions which it laid out, I found this surprising requirement:

Use only approved libraries from the Boost library collection... Some Boost libraries encourage coding practices which can hamper readability, such as metaprogramming and other advanced template techniques, and an excessively "functional" style of programming... In order to maintain a high level of readability for all contributors who might read and maintain code, we only allow an approved subset of Boost features [consisting of roughly five and a half of Boost's nearly one hundred libraries]...

I confess: I love the Boost libraries. I curse my compiler for not supporting Pointer Container. I gaze in awe at the metaprogramming that makes Units and Accumulators possible. I use Format, despite its documented performance problems, because it's so darn convenient. I painstakingly craft Lambda and Preprocessor expressions, in spite of their unforgiving syntax and obtuse error messages, just to have code that's a bit less repetitive and a bit more extensible. (It's truly amazing that the Boost devs have figured out how to add preprocessor-based code generation and lambda expressions to C++.)

But is my approach really best? As already mentioned, the folks at Google are geniuses; maybe they're on to something here? The core goal of the Style Guide authors in restricting Boost seems to be to promote simplicity, which is often in short supply as a software project develops. Some of a project's increase in complexity is unavoidable, as it gains features and adapts to handle real-world problems. Some of a project's increase in complexity is the natural result of entropy and is best handled by a healthy regimen of refactoring. Some of it, though, can only be staved off by a radical commitment to simplicity, as the folks at Google (seem to) suggest, but this raises a number of questions and tradeoffs. For example, is the simplicity of straightforward, somewhat repetitive boilerplate code better or worse than fully generic C++ template wizardry? Is boilerplate code better or worse than depending on a DSL or scripting language to generate code? What about code that's simple to an experienced developer but complex to a novice (or vice versa - code that's simple for a junior developer to write but fails to use simple-to-maintain techniques that a senior developer would know)?  To what extent is it okay to make a class's internals complicated if it makes the class simpler to use? Do I use Lambda and Preprocessor because they're the best tools for the job, or do I use them because I find wrapping my head around them to be a more interesting challenge than maintaining the legacy code base I'm working on? Are the benefits (to my productivity and to future extensibility) of adding a dependency on yet another external library worth the costs to my coworkers and future maintainers of having to understand yet another library before they can work on my code?

At this point in my career, I'm not sure how to answer these questions. I suspect that the approach advocated by the Google C++ Style Guide is flawed; if simplicity is the goal, it's difficult to see how rolling your own IPC or threading library could be simpler than using Boost's, and even small classes and functions like optional and lexical_cast can make code simpler and more readable. However, I suspect that my approach is flawed too; much has been written about the fact that even relatively simple programs are too complex to hold in your head at once, and pursuing the design goals of elegance, extensibility, and robustness without also remembering simplicity can too quickly land you in architecture astronaut territory.

Like I said, I love the Boost libraries. But I've been revising some code I wrote six months ago to no longer use Lambda. It's just simpler this way.

Sunday, January 4, 2009

Floating Point Reference

"Fractions are your friends." This was my high school algebra teacher's standard response when students complained about the sometimes tedious math that they could require. Many years later, I'm finding that while floating point math, while not tedious, is still rather more involved than it appears at first; here's my attempt to summarize issues that may come up.

Floating point data types

In C on an x86 system:
  • A float is 32 bits.
  • A double is 64 bits.
  • A long double is compiler-dependent. A long double in gcc contains 80 bits of data, although it's stored as 128 bits (16 bytes) to maintain word alignment. Visual C++ treats a long double as 64 bits, just like a double (and has been criticized for doing so; see here and here). I had been under the impression that long doubles were nonstandard or were a recent addition to the standard, but as far as I can tell, they've been around since before C99.

Selecting a floating point data type

See this portion of another post.

Floating point storage

This is covered on many sites; the most concise and thorough description I've found is in chapter 2 of Sun's Numerical Computation Guide.

NaNs and Infinity

See my previous post.

Comparing floating point numbers

A simple equality comparison (such as a == b) will often fail, even for values which you would expect to be equal, due to rounding errors (especially rounding introduced by converting between binary and decimal). (Do any compilers or static code analysis tools emit warnings if you try to do a naive equality comparison?)
  • The simplest solution is to check if two floating point numbers are within a small developer-chosen epsilon value of each other; this is the approach used by the CUnit and CppUnit testing frameworks, but it has the disadvantage of requiring you to choose an epsilon value yourself and make sure that it's appropriate for the data being compared.
  • "Comparing Floating Point Numbers," by Bruce Dawson, discusses this absolute epsilon approach as well as more sophisticated approaches such as comparing using a relative epsilon and comparing based on the number of possible floating point values that could occur between the two operands.
  • The simplest good approach, provided by CERT, is to compare using compiler-provided absolute epsilons. (As I understand it, CERT's approach should be equivalent to Dawson's approach with a max ulps of 1.)
Greater than / less than comparisons generally require no special handling, although at the assembly level, a comparison may return a result of "unordered" if NaNs are involved, and one of the compilers I tested (CodeGear C++Builder) fails to account for this and so may return incorrect results when comparing NaNs.

Handling floating point exceptions

See this post.

Low-level floating point calculations

If you need to do floating point work at the assembly level, use Intel Software Developer's Manuals as a reference. Volume 1 has some background on the FPU; volume 2A contains most floating point instructions (since they start with F).

Example code

Rather than simple math, the following code covers manipulating floating point numbers' bit representations, handling NaNs and infinities, and so on.

For further reading

In no particular order...

EDIT: (3/15/2009) Added sections on "Selecting a floating point data type" and "Handling floating point exceptions."

Monday, December 8, 2008

NaNs, Uninitialized Variables, and C++

I've become a big fan of fail fast programming, or what Matthew Wilson colorfully refers to as "hairshirt programming." In other words, if I make a mistake in my code, or if I use a piece of code in a way that violates the assumptions under which it was written, I want to know as soon as possible. C++ is fairly good at doing this at compile time, thanks to a static, reasonably strong, extensible type system, and thanks to add-on features like BOOST_STATIC_ASSERT. For problems that can't be detected at compile time, the liberal use of assertions can help enforce preconditions and postconditions, and classes like std::string and boost::array add error checking over C-style strings and arrays. When I first read about signaling NaNs, I thought that they would be a wonderful addition to this fail fast toolbox. As documented, a signaling NaN is basically magic value that, when assigned to a floating point variable, would cause any attempt to use that variable to throw an immediate exception. This could be an immensely useful tool for tracking down uninitialized variable use and for tracing the operation of legacy code (to answer questions such as, "Is this variable really unused along this code path?"). Unfortunately, signaling NaNs don't work nearly as well as advertised. But first, some background... NaNs are used in the IEEE 754 floating point standard to describe indeterminate forms such as 0/0, ∞ - ∞, 0 * ∞, and so on. NaNs are not the same thing as infinity (either positive or negative infinity). Attempting to do arithmetic on a NaN (almost always) results in another NaN. So if 0/0 is not a number, then 0/0 + 1 is also not a number, and 0/0 * 100 is not a number, and so on. Under some circumstances, this NaN propagation may be what you want; under other circumstances, you may want to catch NaNs as soon as possible (to invoke error recovery, or to launch a separate calculation path, or whatever). Presumably to accommodate this, IEEE 754 distinguishes between quiet NaNs (which quietly propagate when used) and signaling NaNs (which throw exceptions when used). NaNs are represented by storing certain bit patterns in place of a "normal" floating point number. For details, see here. Interestingly, many of the bits in a NaN encoding are unused. (I.e., a NaN can be represented by many different bit patterns.) I've seen suggestions that the unused bits could be used to encode a line number or module number, although I've seen no code that takes advantage of this. C++ supports quiet and signaling NaNs through its std::numeric_limits class template. For example:
#include <limits>
#include <iostream>

int main(int argc, char *argv[])
{
  if (std::numeric_limits<double>::has_quiet_NaN) {
      double d = std::numeric_limits<double>::quiet_NaN();
      std::cout << "The bit pattern of a quiet NaN on your platform is 0x"
           << std::hex << *((long long int*)&d) << endl;
  } else {
      std::cout << "You do not have a quiet NaN for doubles" << endl;
  }
}
Similarly, std::numeric_limits<double>::signaling_NaN() returns a signaling NaN. Unfortunately, as far as I can tell, this feature of the Standard C++ Library is completely useless:
  • If floating point exceptions are enabled, then processing a signaling NaN raises an exception. std::numeric_limits<double>::signaling_NaN()'s returning a signaling NaN counts as processing it.
  • If floating point exceptions are disabled, then processing a signaling NaN transforms it to a quiet NaN.
You can store a signaling NaN to a variable by directly assigning the appropriate bit pattern:
void set_snan(double& f)
{
  *((long long*)&f) = 0x7ff0000000000001;
}
Or, depending on your C++ library implementation, you might find it simpler to steal its signaling_NaN() implementation:
// Assign a signaling NaN using Dinkumware's implementation; works in MSVC
// and C++Builder.
void set_snan(double& f)
{
  memcpy(&f, &_Snan._Double, sizeof(f));
}
Even after you take care of assigning a signaling NaN, making sure that it actually signals is non-trivial:
  • It appears to be somewhat compiler-specific which actions actually raise an exception. Assigning the value of one variable to another does not raise an exception in CodeGear C++Builder but does in Visual C++. The rule seems to be that "anything involving the FPU" can raise an exception if signaling NaNs are involved, and assignment may be done through the FPU or may be done as a memory copy.
  • Raising an exception only occurs if "invalid operation" exceptions are enabled, and there is no portable way of controlling floating point exceptions. C99 specifies the fetestexcept family of functions, at least some of which are also specified in TR1, but of the compilers I tested, only gcc (but not Apple's version!) supports fetestexcept. Visual C++ provides _control87 and _controlfp, which is rather low-level for my taste. CodeGear C++Builder provides Math::SetMaskException, which uses Object Pascal-inspired sets instead of C-style bitmask manipulations but is completely nonportable. If all else fails, you'll have to set the FPU's control word using inline assembly; see here.
  • The floating point exception mask is, as best I can tell, part of the per-thread CPU state. This means that third-party code which your code uses can change it, violating your expectations of which floating point operations will raise exceptions.
To summarize:
  • There is no portable way to assign a signaling NaN.
  • Even if there were, there is no portable way to make sure that performing an operation on a signaling NaN actually signals.
  • It is not entirely straightforward which operations will cause a signaling NaN to signal.
  • Even if you get all of the above right, third-party code may go and mess it up.
So, to conclude, signaling NaNs are probably not a good approach to handling uninitialized variables for the "fail fast" toolbox. In fact, I don't know what practical use signaling NaNs have in the C++ standard at all. Is there a good solution for catching uninitialized variable use? I haven't yet had time to test out options against my code base to see what would work for me, but a few possibilities come to mind:
  • Compiler warnings help, although code complexity can easily exceed a compiler's ability to track uninitialized variables. GCC suffers an additional disadvantage; its uninitialized variable detection depends on its code flow analysis, and code flow analysis is only enabled if optimizations are enabled, so you often won't see these warnings in debug builds.
  • boost::optional works, although that's not a drop-in replacement
  • Never have an uninitialized variable again: use STLSoft's must_init by appending _init_t to all of your fundamental data types (int → int_init_t, double → double_init_t, etc.). Invasive, but an interesting idea...
  • When I asked this question on Stack Overflow, this class was suggested as one possible answer.
  • Signaling NaNs are perhaps the easiest approach and remain an option, in spite of their shortcomings.
Finally, for anyone who's persistent enough to have read this far, here's a complete test program for playing with the various issues raised in this posting. Tested on Visual C++ 2008 and Debian 4.0's g++.
#include <float.h>
#include <iostream>
#include <sstream>
#include <limits>
#include <iomanip>

#if defined(__unix)
#include <fenv.h>
#endif

#if defined(_YMATH)

// (Ab)use Dinkumware's implementation if found.

void set_snan(long double& f)
{
 memcpy(&f, &_LSnan._Long_double, sizeof(f));
}

void set_snan(double& f)
{
  memcpy(&f, &_Snan._Double, sizeof(f));
}

void set_snan(float& f)
{
  memcpy(&f, &_FSnan._Float, sizeof(f));
}

#else

// Add some type safety to our evil, non-portable bit-flipping.
#include <boost/static_assert.hp>
BOOST_STATIC_ASSERT(
  sizeof(long double) == sizeof(long long) + sizeof(long)
  && sizeof(double) == sizeof(long long)
  && sizeof(float) == sizeof(long));

void set_snan(long double& f)
{
  *((long long*)&f) = 0x0000000000000001LL;
  *((long*)&f + 2) = 0x7fff;
}

void set_snan(double& f)
{
  *((long long*)&f) = 0x7ff0000000000001LL;
}

void set_snan(float& f)
{
  *((long*)&f) = 0x7f800001L;
}

#endif

// Return a string containing p's raw bits, in hex value.
// Assume little endian.
template<typename T>
std::string ascii_bits(const T& p)
{
  std::ostringstream o;
  o << "0x" << std::setfill('0');
  for (int i = sizeof(p) - 1; i >= 0; i--) {
    o << std::hex << std::setw(2)
   << int(reinterpret_cast<const unsigned char*>(&p)[i]);
  }
  return o.str();
}

using namespace std;

int main(int argc, char* argv[])
{
  typedef double TYPE_TO_TEST;
  TYPE_TO_TEST f, g;

  // Enable exceptions.  A real app would be more selective and may
  // need to save the previous mask.
#if !defined(__unix)
 _control87(0, _EM_INVALID);
#else
  feenableexcept(FE_ALL_EXCEPT);
#endif

  f = std::numeric_limits<TYPE_TO_TEST>::quiet_NaN();
  cout << "Has quiet NaN?  "
       << std::numeric_limits<TYPE_TO_TEST>::has_quiet_NaN << endl;
  cout << "Quiet NaN is printed like this: " << f << endl;
  cout << "Bit pattern for quiet NaN:      "
       << ascii_bits(f) << endl;

  set_snan(f);

  cout << "Has signaling NaN?  "
       << std::numeric_limits<TYPE_TO_TEST>::has_signaling_NaN << endl;
  cout << "Bit pattern for signaling NaN:  " << ascii_bits(f) << endl;

  g = f;

  cout << "Depending on your compiler, you may see this." << endl;

  g = f + 1;

  cout << "You should never see this." << endl;

  return 0;
}