C++ Craziness

If someone asked you to write a C++ program to output the squares of the numbers from 0 to 9, what would it look like? Vivek Haldar, whose work I’ve cited approvingly several times (1, 2, 3), has an answer. In fact, he has two answers. The point of his post was how the new C++11 makes better solutions possible.

But here’s the thing: the examples are ridiculous. Here’s what I’d do

#include <iostream>
using namespace std;
int main ()
{
  for ( int i = 0; i < 10; i++ )
    cout << " " << i * i;
  return 0;
}

Now look at Haldar’s solutions. To be fair, my code would look the same in old or new C++ so it doesn’t work well as an example of the new functionality that C++11 brings, which is what Haldar is trying to demonstrate. Still, examples like his could easily lead someone to conclude that C++ programmers are crazy. Ironically, Haldar notes that Python has a much more succinct solution based on list comprehensions and hopes that C++ will soon introduce list comprehensions too. But the Python example looks essentially like the code above except that it makes a list first. Why would you do that?

None of this is not to beat up on Haldar, who’s a smart guy and probably wouldn’t actually write code like his examples if he weren’t trying to make a point. It does illustrate a problem in the C++, and more generally the OOP, worlds though. Just because the language provides all those nice templates and object machinery doesn’t mean you should use them to solve simple problems where they aren’t needed. If you do, you end up with examples like the ones we lamented previously.

This entry was posted in Programming and tagged . Bookmark the permalink.