The omnipotent arrow operator

Posted on: 28/12/2009

Are you familiar with the new, all-mighty, arrow “–>” operator in C++ ?

#include <iostream>

int main () {
    unsigned count = 30;
    while (count --> 0) // count goes to zero
        std::cout << count << std::endl;

I believe this is the most intuitive code snippet ever, don’t you agree?

The original stackoverflow question generated some funny comments 🙂

… .. .

But hold on.. We can do even better! How about “<—-" ?

The thing is, that according to operator precedence in C++, the Unary minus operator (-) and the Pre-decrement operator (–) have the same precedence, which causes the Unary minus operator to be evaluated first. Since we cannot (pre)decrement an rvalue (temporary object in our case), we are faced with a compilation error. However, the following workaround is possible through operator overloading:

#include <iostream>

class Count {
        int count_;

        Count (int count) :count_(count) {}

        int &operator-() {
            return count_;

        // solely for making printing easier
        operator int () const {
            return count_;

int main () {
    Count count = 30;

    while (0 <--- count) // count goes to zero, faster?
        std::cout << count << std::endl;

2 Responses to "The omnipotent arrow operator"

Nice! 🙂


Updated, it’s even funnier now. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 27 other followers


%d bloggers like this: