0
#include<bits/stdc++.h>
using namespace std;


int count;
int main()
{
    int k;
    cin>>k;
    count=k;
    cout<<count;
    return 0;
}

I am trying to change the value of 'count' (Global Variable) in main function but getting reference to 'count' is ambigous error in C++. But the same kind of code works well in C. Please help me.

lovelorn
  • 27
  • 2
  • 5
    This is why [`#include` is bad](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [`using namespace std;` is bad](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and combined together they are horrible. `std::count` exists and now your compiler is confused what do you mean by `count`. – Yksisarvinen Jun 09 '20 at 15:10
  • 4
    Include what you actually need and don't drag the entire standard library into the global namespace. `#include` and `using namespace std;` are convenient, but they also have a cost. – molbdnilo Jun 09 '20 at 15:11
  • @Yksisarvinen I changed the variable name from "count" to something else. But still getting the same error. – lovelorn Jun 09 '20 at 15:51
  • `namespace std` is full of very common names, quite likely to that you shot into another one. The correct solution is to get rid of both `#include` and replace it with `#include ` (and in futere any header that you need) and get rid of `using namespace std;` and use qualified names: `std::cout` and `std::cin` (eventually you can change `using namespace std;` to `using std::cout;` and `using std::cin;`, if you really want to save that 5 characters when printing and reading input) – Yksisarvinen Jun 09 '20 at 16:02

1 Answers1

3

Remove the using namespace std; line, add the std:: to cin and cout and it should be ok.

You have this compiler error because std::count exist: https://en.cppreference.com/w/cpp/algorithm/count
So it's ambigous for the compiler between std::count and your variable count because you use using namespace std.

Yksisarvinen
  • 13,037
  • 1
  • 18
  • 42
MatthieuL
  • 474
  • 1
  • 1
  • 7