A simple “counter” example, C, C++, Python

Counter is a very simple class. In fact it is meant to be used “as a function”. In C you would have used a static variable, for example:

counter.c (download)
int counter(){
    static int n  = -1;
    return n;

Although the C version is shorter, the Python (or C++) solution is cleaner. In fact counter() is a function, but it also contains data. From a logical point of view, it should be a class. In fact in C++ it would have been:

counter.cc (download)
class Counter{
    int n_;
    Counter() : n_(0) {}
    Counter(int i) : n_(i) {}
    int operator()(){
        return n_++;

Notice that the Python version permits to define a custom function to set the step of the counter. Of course this could have been done also in C or in C++, but the result would have been a bit longer.
After the class definition, we show a typical use of the counter.

counter.py (download)
class Counter(object):
    def __init__(self, fvalue=0, inc = lambda x: x + 1):
        self.inc = inc
        self.val = fvalue
    def __call__(self):
        old = self.val
        self.val = self.inc(self.val)
        return old
c = Counter(1)
print [ c() for i in xrange(0, 10)]

6 Responses to A simple “counter” example, C, C++, Python

  1. be'tor says:


  2. Anna says:

    That helped me alot :3
    Thank you ♥


    sir i need the full syntax of constructor in c++,i must be easy to understand .i AM REALLY THANK FULL TO YOU

  4. VB.Net, C#, C++…

    […]A simple “counter” example, C, C++, Python « RiK0\’s Tech Temple[…]…

  5. Hey there! This is kind of off topic but I need some help from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m
    thinking about creating my own but I’m not sure where to start. Do you have any points or suggestions? Many thanks

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

%d bloggers like this: