I'm aware of the "avoid global variables" rule (and how you can still use them in specific cases and when you know exactly what you're doing), but I also know that a variable can only be used if it was declared before the code block trying to use it.
So I know in this case
a is a global scoped variable that is visible in both functions:
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
int a=10;
void function1()
{
a=5;
}
int main()
{
function1();
std::cout << a;
}
| |
But this is where I start to get confused:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
void function1()
{
a=5;
}
int a=10;
int main()
{
function1();
std::cout << a;
}
| |
In this case I'll get an error saying that variable
a wasn't declared in function1's scope.
So my first question is: on the second example, is variable
a still a global variable?
Now for a third example, since the variable isn't on function1's scope, let's pass it as an argument:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
void function1(int & x)
{
x=5;
}
int a=10;
int main()
{
function1(a);
std::cout << a;
}
| |
Is it good or bad practice (or maybe neither) to declare variable
a that way? Are there any pros or cons of declaring variables like this?
I've seen code where variables that should be local to main are declared right before the main function definition and I don't see why they chose to do it like that.
Thanks.