-4

I got the following problem:

When I use this code

#include <iostream>

int count = 10; /* Global variable */

int main() {
   while(count--) {

   }
   return 0;
}

the code compiles perfectly well. However, if I add "using namespace std;" then I get the error message "count undeclared" in the while-loop. The same is also true if I add "static" before "int count". I am new to C++ so I have not fully understood scopes etc. Can somebody explain? Thanks in advance!

Yinyue
  • 145
  • 1
  • 3
  • 12
  • 2
    [No repro](http://coliru.stacked-crooked.com/a/667974613315759d). Post a [MCVE] of the non working code please. – πάντα ῥεῖ Mar 04 '17 at 10:23
  • 1
    Could you please write in the `using namespace std;` statement into the code for everybody's reference. Also, what compiler are you working with? I was not able to reproduce it: http://coliru.stacked-crooked.com/a/8b9ef25d202c5af9 – batbrat Mar 04 '17 at 10:30
  • The question shows code that **works** but should show the code that **doesn't work**. – Pete Becker Mar 04 '17 at 18:31

3 Answers3

3

name space std also declares name count. This name corresponds to the standard algorithm std::count. So when you include the directive

using namespace std;

and when use unqualified name count like this

while(count--) { //... }

then there can be an ambiguity.

To resolve the ambiguity you should use a qualified name. For example

    using namespace std;

    //...

   while( ::count--) {
          ^^^^^^^^
       //...
   }

In general it is not a good idea to use the directive that can lead to such an ambiguity as in your example.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

this is happening because the name 'count' has another definition in std llibrary. look here - http://en.cppreference.com/w/cpp/algorithm/count.

std::count

Count is a template definition that was definted in the standart library, after using the using namespace std the compiler cant tell between the count varable and the count template from the std lib. you might wanna change count integer name :)

Sivan
  • 11
  • 2
0

Don't be confuse, simply use this ::count /* :: is a prefix operator used to call global variables */ use :: operator whenever you need to call a global variable.

Snigdh
  • 61
  • 11