2012-03-09

operator<< and function pointers

This one fools me all the time. Maybe if I write it down I'll remember.

What does this code output?
#include <iostream>
int main() {
 std::cout << main << std::endl;
 return 0;
}

When I see a function pointer shown as "1", my first thought is "Thumb2 bug". ARM processors use odd addresses to mean "there's Thumb2 code at (address & ~1)", so a code address of 1 looks like someone accidentally did (NULL | 1).

What's really happened here, though, is that several design decisions have conspired to screw you. Firstly, function pointers aren't like normal pointers. If you reinterpret_cast<void*>(main), say, you'll get an address. (Though what exactly you get the address of in C++ can get quite interesting.) Then the ancient evil of the implicit conversion to bool comes into play, and since your function pointer is non-null, you have true. Then there's an operator<<(std::ostream&, bool), but the default stream flags in the C++ library shows bool values as 1 and 0. You need to explicitly use std::boolalpha to get true and false.

So what you're really seeing here is "you have a non-null function pointer". Which is almost never what you intended.