13
#include<iostream>
using namespace std;

void callMe()
{
    int count=0;
    cout<<"I am called "<<++count<<" times!\n";
}

int main()
{
    callMe();
    callMe();
    callMe();
    callMe();
    return 0;
}

In this case, the output will be

I am called 1 times!
I am called 1 times!
I am called 1 times!
I am called 1 times!

Instead, I want the output printed as

I am called 1 times!
I am called 2 times!
I am called 3 times!
I am called 4 times!
0

9 Answers 9

42

I hope that the following code snippet will solve your issue!

#include<iostream.h>

void callMe()
{
    static int count=0;
    cout << "I am called " << ++count << " times!\n";
}

int main()
{
    callMe();
    callMe();
    callMe();
    callMe();
    return 0;
}

Here the static variable will retain its value and it will print the count incremented each time!

12
  • 13
    It is not global, it's visible only inside callMe().
    – Joker_vD
    Nov 26, 2012 at 10:41
  • 3
    there is no need to initialize count since it is a static variable. Nov 26, 2012 at 10:46
  • 16
    @Praveen Vinny still it is rather good idea to initialize it. Explicit is better than implicit in most cases (especially if more than one person will be reading that code at some point later on) and getting into good habits is something that should be encouraged.
    – elmo
    Nov 26, 2012 at 11:13
  • 7
    That's because initialization only sets the initial value. What if you want a different initial value to zero?
    – Useless
    Nov 26, 2012 at 11:38
  • 8
    While I think it is best practice to explicitly initialize a static var, according to this SO question, the C++ spec says that static vars will be set to zero if you don't do it yourself stackoverflow.com/questions/1294772/…
    – Peter M
    Nov 26, 2012 at 12:42
24
void callMe()
{
    static int count = 0; // note 'static' keyword
    cout<<"I am called "<<++count<<" times!\n";
}
11

make a static variable

so define it in function itself and due to property of static it will retain it's value in each call.

void callMe()
{
    static int count=0;
    cout<<"I am called "<<++count<<" times!\n";
}

static storage is done in data segement it's not on the function stack so in each call function will take it's modified value . So it will print your desired result.

but the count you have declared is local and have storage on stack so for each function call it always takes count = 0

11

3 ways actually, 2 of them have already been mentioned here. I would summarize along with reasons:

1) Declare the variable as Static:

void callMe()
{
    static int count=0;
    cout<<"I am called "<<++count<<" times!\n";
}

This works because the memory now creates a single copy of count, instead of creating one every time the function is called and then deleting it when the function is done. Also worth noticing here is that count is still Local to the function i.e. if you try to do something like this:

int main()
{
    int count;
    callMe();
    callMe();
    callMe();
    callMe();
    cout<<"you called "<<count<<"functions!\n";
    return 0;
}

count will still display a garbage value because the count for your function and count for your main are 2 different variables in 2 different locations.

2) Intialize a global variable:

int count=0; 
void callMe()
{
    cout<<"I am called "<<++count<<" times!\n";
}

In the above example, the variable has a scope that is global therefore the whole program uses a single copy of the variable, and hence the changes made somewhere will reflect everywhere in the program. You can use this approach if you need to monitor more than 2 functions. for eg:

int count=0;
void callMe()
{
    cout<<"I am called "<<++count<<" times!\n";
}

void callMe2()
{
    cout<<"I am called 2 "<<++count<<" times!\n";
}

int main()
{
    callMe();
    callMe();
    callMe2();
    callMe2();
    cout<<"you called "<<count<<" functions!\n";
    return 0;
}

Since count here is basically common to both the functions and the main, they all refer to the same value instead of making their own local copies. Could be messed up if you have variables with same name. To understand difference between global and static variable and their scope click here

3) Pass a reference of the variable:

void callMe(int &count)
{
   cout<<"I am called "<<count++<<" times!\n";
}

void callMe2(int &count)
{
   cout<<"I am called 2 "<<++count<<" times!\n";
}

int main()
{
    int count=0;
    callMe(count);
    callMe(count);
    callMe2(count);
    callMe2(count);
    cout<<"you called "<<count<<" functions!\n";
    return 0;
}

This is probably the cleanest way to do this, the variable is local to the main (which would save you garbage collection complications) and since this is a pass by refrence, all changes made point to the same location in the memory. If you don't have a solid reason not to follow this, I would say use this.

Hope I didn't confuse you further, Happy hunting.

4
  • 1
    @Punkeshwar-The way of doing it using call by reference is appreciable! But the static variable concept is more agreeable for a beginner! And I couldn't agree with what you had told of the garbage values in the first part of your answer! When we are not using it out of the local scope, there is no question of a garbage value here! Nov 26, 2012 at 12:56
  • @PraveenVinny Count is not initialized in main(), even if it was, its value would not change because of the functions (which was the point of displaying it in main()). I missed declaring the variable, updating the answer accordingly hope the garbage value scenario becomes clearer.
    – IndianNoob
    Nov 26, 2012 at 16:45
  • Granted that I haven't done any C++ programming, but if I needed to monitor more than one procedure, I'd probably extract the count-variable portion to a new procedure, that they both reference, not to a global variable. Nov 26, 2012 at 22:53
  • @Clockwork-Muse it was more to show him how global variable and static variable would differ... as I mentioned passing references is the preferred method. I am just providing him alternatives with a little background.
    – IndianNoob
    Nov 27, 2012 at 15:54
6

You will have to pass it as an argument or store it as function state.

int count = 0;
auto callMe = [=] mutable {
    cout<<"I am called "<<++count<<" times!\n";
};
1
  • I'm curious about the significance of the mutable keyword in this example. Edit: Ah, I see that captures in closures are const-by-default.
    – Steven Lu
    Nov 26, 2012 at 19:27
6

If you want to count the number of calls of a single function you could indeed use the static counter variable.


Alternatively, if you want to do this for debug purposes it's not the worst idea to use a profiling tool for this. For example Valgrind's Callgrind [emphasis mine]:

Callgrind is a profiling tool that records the call history among functions in a program's run as a call-graph. By default, the collected data consists of the number of instructions executed, their relationship to source lines, the caller/callee relationship between functions, and the numbers of such calls.


When you use gcc you could also tinker around with the __PRETTY_FUNCTION__ macro and a global map:

#include <iostream>
#include <string>
#include <map>

std::map<std::string, int> call_counts;

void call_me_one() {
    call_counts[__PRETTY_FUNCTION__] += 1;
}

void call_me_two() {
    call_counts[__PRETTY_FUNCTION__] += 1;
}

void call_me_three() {
    call_counts[__PRETTY_FUNCTION__] += 1;
}

int main()
{
    for (int i = 0; i < 10; i++) 
        call_me_one();

    for (int i = 0; i < 20; i++) 
        call_me_two();

    for (int i = 0; i < 30; i++) 
        call_me_three();

    for (auto it = call_counts.begin(); it != call_counts.end(); ++it)
        std::cout << (*it).first << " was being called " 
            << (*it).second << " times.\n";
}

Here's the output on my machine:

void call_me_one() was being called 10 times.
void call_me_three() was being called 30 times.
void call_me_two() was being called 20 times.
3

You have to use "static" keyword before count.

Rectified Code Snippet will be something like this:*

void callMe()
{
    static int count;
    cout<<"I am called "<<++count<<" times!\n";
}
0
2

You can pass the variable count by reference and increase it every time the function is called like this:

void callMe(int &count)
  {
     cout<<"I am called "<<count++<<" times!\n";
  }

int main()
  {
    int count=0;
  callMe(count);
  callMe(count);
  callMe(count);
  callMe(count);
  return 0;
  }

For more information about passing-by-reference you can refer here.

1

Essentially what everyone here suggests. This is a macro I've used from time to time. I find it makes for easier reading.

in a separate header: (say debug_helper.h)
---------------------
#define COUNT_USAGE() {static int count=0;++count;std::cout<<"Called "<<count<<" times\n";}

In the CPP file:
----------------
#include "debug_helper.h"    

void callMe()
{
    COUNT_USAGE();
}
4
  • I dont understand why you want another header file to store a function. The program's compilation time will increase when you use an external file.
    – user1852957
    Dec 12, 2012 at 2:10
  • It's not a function. Its a macro. Its stored in a separate file because cleanliness of the code is more important than the miniscule increase in compile time. It also means I can re-use the same macro in other source files.
    – Carl
    Dec 12, 2012 at 2:22
  • It doesn't make sense when you just give importance to the cleanliness of the code. I would prefer machine efficient code rather than clean code. But I am not against giving indentations to improve the formatting of the code.
    – user1852957
    Dec 13, 2012 at 8:40
  • 1
    @AbyWang I'm not going to and convince you that readable code is preferable. You'll convince yourself over time.
    – Carl
    Dec 13, 2012 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.