How to contribute questions for cppquiz.org


You might be familiar with my C++ quiz site, cppquiz.org. But did you know you can contribute your own questions to the site? First, try solving a few questions to get the gist of it, then visit http://cppquiz.org/quiz/create to create your own.

I try to live by the “quality of quantity” motto for the questions on the site, so you’ll find the following guidelines on the submission form:

  • Your question should be short, and demonstrate one thing only
  • Your question should compile (unless not compiling is the point)
  • Your question should be about standard C++, not compiler specific or about 3rd party libraries
  • Your question should not be a trick question, and be free from distractions
  • Your explanation should be clear and to the point
  • Your explanation should use correct terminology, and refer to the standard where possible
  • Prefer well defined programs over programs with compilation errors, undefined or unspecified behaviour

But what does all of that mean?

Your question should be short, and demonstrate one thing only

The shorter the code in the question, the better. The point of a question is to teach one single aspect of C++, not to be an exercise in reading and understanding an unfamiliar code base.

Your question should compile (unless not compiling is the point)

It should be possible to copy your code verbatim and have it compile as C++11, without errors, requirements for additional includes etc. (Of course, some questions are not intended to compile, then this rule does not apply.)

Your question should be about standard C++, not compiler specific or about 3rd party libraries

This should be fairly self explanatory, don’t make questions about posix, boost, windows.h etc.

Your question should not be a trick question, and be free from distractions

I’ve refused several questions due to this. Your question is supposed to be non-trivial, but the difficulty should be to understand a concept of C++, not to read the question correctly, or find the clue in the midst of distractions. Don’t make questions where the key is noticing that the variables v1 and vl are not the same. Don’t make questions full of complicated C++ that doesn’t matter, but is just there to hide the simple core of the question.

Your explanation should be clear and the point

Don’t go on lengthy asides in the explanation. As your question is already short and demonstrates one thing only, explaining that single concept should not take too many words.

Your explanation should use correct terminology, and refer to the standard where possible

The chances of having your question published quickly increases if you use correct C++ terminology to describe the concepts in your question. It helps me a lot if you’re also able to provide references to the standard, but don’t let this stop you from contributing.

Prefer well defined programs over programs with compilation errors, undefined or unspecified behaviour

There’s a lot of fun and interesting things to learn from questions that don’t compile, or contain undefined or unspecified behaviour. It’s however not so fun when most of the questions on the site can be answered simply by enumerating those three alternatives as an answer.

That’s it! I hope I didn’t scare you away from contributing. Please have a go, and don’t be afraid to ask if you have any questions about your question! :)

All C++ talks from NDC now available


As I’ve previously posted about, there was a great C++ track at NDC this year. It turns out that videos of all the talks are now out. Big thanks to Olve Maudal for putting together this track! And thanks to all the speakers for interesting talks and some nice chats.

You can see my talk “So you think you can int” here, and find my slides here.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Posted in C++. Tags: , , . 2 Comments »

Very Strong C++ Track at the NDC Conference


As someone who doesn’t do web development, and didn’t use to do any .net, I’ve not always been too excited by the Norwegian Developers Conference agenda. This year however, I’m very impressed by the C++ track organized by Olve Maudal et. al.

First of all, there’ll be no less than 13 talks, by Nico Josuttis, Scott Meyers, Andrei Alexandrescu, Hubert Matthews, Mike Long, Isak Styf, Ismail Pazarbasi, Olve Maudal, and myself. In addition, Andrei Alexandrescu will give a two day workshop. Here’s the full list:

ndc

See the full agenda at ndcoslo.com, especially Wednesday and Thursday. I’ll be talking about ints. If you think that sounds like a narrow topic, rest assured there’ll be a char too! Oh, and a secret tip, if you’re a member of Oslo C++ Users Group, contact me for a discount!

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Posted in C++. Tags: , , . 3 Comments »

New job!


Today was my first day at my new job as a staff engineer at Outracks Technologies. Outracks is a small startup in Oslo creating Uno, the world’s first hybrid CPU/GPU programming language, and Realtime Studio, a powerful, easy-to-use IDE for real-time graphics in 2D and 3D. In other words, theywe’re the coolest technology company in Norway! :)

For a one-minute intro to Realtime Studio, check out the brand new product video. Today also marked the release of the Faraday milestone release, which comes with a video of its own. If you want to check out Uno and Realtime Studio, don’t hesitate to sign up for the closed beta!

Discovering the demoscene back in 1995 was the main reason I got into programming in the first place, and with this job it really feels like I’ve come full circle.

Since Uno is not C++ (even though it compiles down to it on several of our target platforms), I will probably not post much more about it here. If you’re interested in keeping up, you can follow me and Outracks on Twitter, and like Outracks on Facebook.

CppQuiz.org officially launched!


The Story (you can skip this part)

Back in April I went to the excellent ACCU 2013 conference. I had been playing with the idea for an online C++ quiz for a while, but decided I didn’t have the time to do it. Then, after a few glasses of wine at the conference dinner and a few more Bath Ales in the bar, I went to my room to get some sleep. But it couldn’t hurt to do a little bit of coding, could it? Add to that the train to London next day, and the plane to Oslo, and the first version of CppQuiz.org was born.

I spent a few more days on it this summer, and since then it has been functionality complete (enough) and stable, so today I removed the “beta” header. I also realised I had forgotten to blog about it, which is kind of silly. How to market a quiz about C++? What about on your own C++ blog?

What is it

CppQuiz.org is (as you might have guessed by now) an online C++ quiz. Each question is a full C++ program, and you are to figure out what its output is. I stole this format from Olve Maudal‘s pub quizzes, but with one major difference: While his quizzes are about what happens on his computer (which is very interesting for a more interactive format), CppQuiz.org asks about what the standard mandates the output to be. If the example code doesn’t compile, or has unspecified/undefined behaviour, you answer that.

The site will just keep throwing questions at you (training mode), optionally giving you a hint and finally give you a full explanation of the answer, with references to the C++11 standard. If you want, you can however start a new quiz (quiz mode), and get a fixed number of questions. At the end you get a score, and a link to give your friends to see if they can beat you. Neither mode requires you to register or log in.

How you can help

If you like the quiz and want to help, there are many ways to do so:

Thanks guys!

Finally I wish to thank a few people. Olve Maudal gives the world’s best C++ pub quizzes, and was my biggest inspiration for creating the site. He also has a fascinating, deep understanding of C and C++, and is an all-around great guy. He even sent me all his C++ quiz material to use for inspiration. See, I told you he is a great guy.

Several people have also contributed their own questions. KrzaQ2 did several, Lars Storjord and others also did. Mikael Kilpeläinen and Fernando Cacciola sent me some of their material. Jon Jagger, Peter Sommerlad, Björn Fahller and several other ACCU members provided good feedback. (I do hope you’re an ACCU member?) Oh, and Webfaction is a highly recommended hosting company. They don’t sponsor me or anything, but their customer service is the best.

Now go take the quiz!

If you enjoyed this post, you can subscribe to my blog, or follow me (@knatten) or @CppQuiz on Twitter.

Posted in C++. Tags: , , . 8 Comments »

Prefer Using References With Range Based For Loops


Now and again I see people forgetting the & in range based for loops, like this:

    for (auto a : a_vec)
    {
    }

What some people seem to forget, or don’t know, is that this creates a copy of the element for each iteration. Unless you actually need a copy, there is no need to perform it. And if the objects you are copying are any larger than a built-in type (integer, pointer etc.), there is a potential performance penalty. So by default, do this instead:

    for (const auto& a : a_vec)
    {
    }

Notice the &? Now you get a reference instead of a copy, which is typically cheaper. Here is the full program:

#include <iostream>
#include <vector>

using namespace std;

class A
{
public:
    A() = default;
    A(const A& rhs) { cout << "Copy" << endl; }
};

int main()
{
    vector<A> a_vec(2);

    cout << "Range based for without &" << endl;
    for (auto a : a_vec)
    {
    }

    cout << "Range based for with &" << endl;
    for (const auto& a : a_vec)
    {
    }
}

And its output:

Range based for without &
Copy
Copy
Range based for with &

Afterthought: Why?

Why are people doing this? It might be that people are used to iterating with iterators, where you get a cheap copy of the iterator, not the actual object:

    for (auto a = a_vec.cbegin(); a != a_vec.cend(); ++a)
    {
    }

Here, a is an iterator, not the actual object, so copying it is inexpensive.

As usual, the code for this blog post is available on GitHub.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Fighting FUD – Introducing C++11 to Legacy Programmers


I’m at the ACCU 2013 conference, and this morning Bjarne Stroustrup held a keynote about C++11. One of his points was that full adoption of C++11 will take some time, due to compilers, libraries etc. lagging behind, but also due to many programmers not wanting to use new things in general. What can you do about it? Bjarne briefly suggested we fight the FUD by starting to introduce the very simplest features that just make everyone’s lives easier. Here is my take on that.

Simple feature #1: Uniform Initilaization

Initializing containers used to be painful. For example, initializing a vector of ints required a long list of push_backs, or something like this:

    int tmp_v[] = {1, 1, 2, 3, 5, 8};
    vector<int> old_v(tmp_v, tmp_v + sizeof(tmp_v) / sizeof(tmp_v[0]));

Now however, we can do this:

    vector<int> new_v = {1, 1, 2, 3, 5, 8};

Even the most hard-core “I don’t need all that new stuff” legacy programmer will appreciate that. Btw, I think this is especially useful in unit tests, where you typically initialize a lot of data manually. (Those legacy programmers probably “don’t need all that new unit testing stuff” either, though.)

This becomes even more important when you have more complex containers:

    vector<pair<int, string>> ints = {{1, "one"}, {2, "two"}};

Simple feature #2: Type deduction

Let’s say we want to print out that vector of pairs from the previous example. This is how you’d do it in C++03:

    for (vector<pair<int, string>>::const_iterator it = ints.begin(); it != ints.end(); ++it)
    {
        cout << it->first << ":" << it->second << " ";
    }

That vector<pair<int,string>>::const_iterator is a bit cumbersome, right? Well, in C++11 we can let the compiler figure out the type for us:

    for (auto it = ints.begin(); it != ints.end(); ++it)
    {
        cout << it->first << ":" << it->second << " ";
    }
    cout << endl;

Note that auto is resolved compile-time, this is not dynamic typing. But we can do even better:

Simple feature #3: Range based for

    for (auto& elm : ints)
    {
        cout << elm.first << ":" << elm.second << " ";
    }
    cout << endl;

This really is as simple as it gets. Notice that the type of elm is no longer an iterator, it is a reference to the element. This means you no longer have to dereference the iterator, and things become even simpler. (Not having to dereference is a bigger issue when the containers store pointers, and you end up doing (*it)->member.)

(Not so?) simple feature #4: Lambdas

The first three features should be fairly simple to convince anyone to use. I would however argue that it should be fairly simple to make an argument for the simplest uses of lambda functions too.

Lets say we want to find an element in that vector<pair>. To do that, we need a predicate function/functor. In C++03, we would need to either do something with std::bind_1st / std::bind_2nd, or write our own predicate like this:

    class CompareString
    {
        public:
            CompareString(string s) : s(s) {}
            bool operator()(const pair<int,string>& p) { return p.second == s; };
        private:
            string s;
    };

    auto it = find_if(ints.begin(), ints.end(), CompareString("two"));

We are not really interested in making that class. All we want is the content of operator(). Wouldn’t it be nice if we could just paste that code directly in the call to find_if? Something like this?

    auto it2 = find_if(ints.begin(), ints.end(),
        bool operator()(const pair<int,string>& p) { return p.second == "two";});    

With lambdas, we can:

    auto it2 = find_if(ints.begin(), ints.end(),
        [](const pair<int,string>& p) { return p.second == "two";});    

For the purpose of this article, [] can be read as “lambda function follows:”. Notice that we don’t even have to specify the return type, as it can be deduced by the compiler.

Conclusion

That’s it! Just a few simple things to start introducing in you code base, to fight the FUD and convince the legacy programmers that C++11 is nice. (And sorry if this blog post feels a bit rushed, I wrote it during lunch at ACCU 2013. Now I’m off to see my friend Mike Long talk about legacy code base restoration projects.)

As usual, the code for this blog post is available on GitHub.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.