The omnipotent arrow operator

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 (a 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_;

    public:
        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 thoughts on “The omnipotent arrow operator

Leave a Reply