Hey. I'm reading up on the beginner's guide from msdn.com and i've come to learn the basics, however when i try to compile a program that explains the differences in global and local variables it says that my global variable is not global and therefor will not execute inside my function.
Here is my code and the error message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
void func1();
void func2();
int count;
int main ()
{
int i;
for (i=0; i<10; i++) {
count = i * 2;
//func1();
}
return 0;
}
1 2 3 4 5 6 7
func.cpp: In function `int main()':
func.cpp:14: error: use of `count' is ambiguous
func.cpp:7: error: first declared as `int count' here
../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bits/stl_algo.h:413: erro
r: also declared as `typename std::iterator_traits<_Iterator>::difference_type
std::count(_InputIterator, _InputIterator, const _Tp&)' here
func.cpp:14: error: `count' was not declared in this scope
From your error message is seems that by your statement "using namespace std;" you have dragged all the names from your std include files into the global namespace.
So your compiler is not able to tell is it is YOUR count that you want to use or the count from the std namespace.
It is best to always avoid the statement "using namespace std;"
It happens because namespace std has template function with name count so it's conflict of names.
To solve it and avoid one please don't use "using namespace std"(or other namespace)
so more correct variant is
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
int count(0);//it's good idea to init variable where it's declared
int main ()
{
for (int i(0); i < 10; ++i)//it's good idea to declare variable is local as possible
{
count = i * 2;
}
return 0;
}
#include <algorithm> // contains symbol std::count
usingnamespace std; // moves symbol std::count into just count (global)
void func1();
void func2();
int count; // Now this count clashes with the count you brought into the global namespace above
int main ()
{
int i;
for (i=0; i<10; i++) {
count = i * 2; // Hence the error, which count to use? Yous or the one from the #include?
//func1();
}
return 0;
}
When you use "include namespace std;" you move a LOT of names into the global namespace. These names are therefore no longer available for you to use. You have to avoid them.
This is why it is not considered best practice to use "using namespace std;" for anything other than trivial programs.
yes i read that it is not recommended to use global variables, but you know, im learning, its quite wierd that microsoft's beginner's guide then use the namespace and then in conflict with "count"
but thank you all for your great meaningful and describing answers