1

I am implementing quickSort using my own namespace alg.

namespace alg
{
    static unsigned int comparisons(0);
    void quickSort (std::vector<int>& a);
    int partition (std::vector<int>& b, int leftIndex);
}

I need to count comparisons of elements in the array, for that reason I use static variable comparisons that GETS incremented in functions but in main.cpp it still stays 0.

What is wrong? Why in main.cpp I guess for every .cpp file there is a serapate static variable comparisons, but I am not sure. Anyway, how can I fix this? Do I actually need to write a class where I can keep a static variable? Or that still won't help?

And Please suggest where can I find detailed information on static variables and namespaces?

QuickSort.cpp

void alg::quickSort(std::vector<int>& a)
{
....
    comparisons+=1;
}

int alg::partition(std::vector<int>& a, int leftIndex)
{
   comparisons+=a.size()-1;
....
}

main.cpp

alg::quickSort(myvec);
...
std::cout << alg::comparisons << std::endl;
Uylenburgh
  • 1,277
  • 4
  • 20
  • 46
  • 2
    You might want to show the lines changing the variable and using it. Global variable retain their values. BTW, a **much** better approach to count operations it to pass in the comparison function as a function object and have that contain a counter using, e.g., a pointer to a local variable in `main()`: global variables are bad. – Dietmar Kühl Jan 03 '14 at 19:23
  • " I guess for every .cpp file there is a serapate static variable comparisons, but I am not sure. Anyway, how can I fix this?". Remove static – deviantfan Jan 03 '14 at 19:24

2 Answers2

5

A namespace-scope variable declared static has internal linkage, which means that every translation unit (=.cpp file) gets its own copy. So what's likely happening in your case is that the copy in the file implementing quicksort and partition is incremented, but the one in main() is not.

What you need to do is replace the static keyword with the extern keyword (to make that line just a declaration), and then define the variable in one .cpp file (probably the one implementing quicksort and partition):

namespace alg
{
  unsigned int comparisons = 0;
}

As for finding more information on this, refer to your favourite good C++ book.

Community
  • 1
  • 1
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

Why in main.cpp I guess for every .cpp file there is a serapate static variable comparisons, but I am not sure

That's right.

Namespace-static means it's file-local. This is not the same as class-static.

You probably meant to use extern.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Ah yes, this explains the OP's confusion. The tendency of C++ standards writers to reuse existing keywords has struck another blow! (They tend to do that because every new keyword breaks existing code: by reusing `static` from C, more C code compiled in C++) – Yakk - Adam Nevraumont Jan 03 '14 at 19:45