Tue Apr 17 08:11:59 EDT 2012

gcc why you gotta hurt me so

I got tired of being apparently the last person in the world not to know C++. So I'm struggling through one of those stupid "Teach yourself X in only one hour a day" books, and because I'm me, I'm wasting a lot of time haring off on pointless tangents. Like, for one example, the auto operator.

From "The Biggest Changes in C++11 (and Why You Should Care)":

In C++03, you must specify the type of an object when you declare it. Yet in many cases, an object’s declaration includes an initializer. C++11 takes advantage of this, letting you declare objects without specifying their types:

auto x=0; //x has type int because 0 is int
auto c='a'; //char
auto d=0.5; //double
auto national_debt=14400000000000LL;//long long

This sounded like a new and innovative way to shoot yourself in the foot, so I gave it a try. And it works great! For those examples, and those examples only.

auto Array[5] = { 1, 2, 3, 4, 5 };

You'd think it would be pretty obvious that I want a five element array, initialized with 1 ... 5, right?

$ g++ -pedantic -std=gnu++0x -Wall -Wextra -Werror foo4.cc
foo4.cc:5:33: error: unable to deduce ‘std::initializer_list [5]’ from ‘{1, 2, 3, 4, 5}’

C'mon, man. Please?

(There's also a really neat GCC feature called designated initializers, which offers an abridged syntax for initializing an array with sequential values. C only, sucker! Anyone using C++ can fuck off, apparently.)

GCC is also really bad at reading minds:

auto a = 3;
auto b = 2;

int main()
  cout << a / b << endl;

Which, of course, outputs:

$ compile foo5.cc && ./a.out

This is because an operation on an int will always output another int. Knowing what little I do about C internals, I had been half-hoping that it would do a little static analysis here and figure out it needed to use floats here, but no. To me, Python strikes a much better balance here with its dynamic+strong typing, between the icy rigor of Haskell, and the freewheeling madness of PHP's type system. C++11's abstraction is too leaky to be useful, which means you're better off explicitly decalring types than trusting auto to do what you mean.

Posted by Samuel Bierwagen | Permanent link | File under: nerdery