1

I'm begginer in C++ using Xcode. I get error using Xcode C++ when trying to use declared global variable. Here is example code.

#include <iostream>
using namespace std;

int count ;

int main()
{
    count=1;     // reference to 'count' is ambiguous

    cout << count;  // reference to 'count' is ambiguous

    return 0;
}

Thank you.

3 Answers3

4

There is an STL algorithm named std::count() and as there is a using namespace std; directive the compiler now has two available count symbols to choose from: remove the using namespace std; and use std::cout.

See Using std Namespace for further reading.

Community
  • 1
  • 1
hmjd
  • 117,013
  • 19
  • 199
  • 247
  • 1
    Everytime someone says `using namespace std;`, god eats a baby kitten. – Kerrek SB Oct 09 '12 at 16:24
  • Thanks, i've uderstood that i didn't know about STL algorithm named std::count(). I just learning global variables on simple examples. I've changed the variable's name to "count1" and it works. – blackishharry Oct 09 '12 at 16:49
1

Either remove the using namespace std; or qualify the use of your variable ::count:

int main()
{
    ::count=1;     // reference to 'count' is ambiguous

    cout << ::count;  // reference to 'count' is ambiguous

    return 0;
}

You get the ambiguity because of std::count.

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
  • Thanks, i've uderstood that i didn't know about STL algorithm named std::count(). I'm just learning global variables on simple examples. I've changed the variable's name to "count1" and it works. Thank you. – blackishharry Oct 09 '12 at 16:52
1

Remove the using namespace std; and change cout to std::cout. That using declaration pulls all of the standard library names into the global namespace, and their's an algorithm named std::count that's probably the source of the problem. In general, using namespace std; is a bad idea.

Pete Becker
  • 72,338
  • 6
  • 72
  • 157
  • Thanks, i've uderstood that i didn't know about STL algorithm named std::count(). I'm just learning global variables on simple examples. I've changed the variable's name to "count1" and it works. – blackishharry Oct 09 '12 at 16:53