Hi,
im a beginner in C++. if a static variable is defined globally , what will be the scope of the variable in any of the functions used ... will the scope of the variable will be local to that function?
#include <iostream>
constint number = 10;
using std::cout;
using std::endl;
int main()
{
int number = 5;
cout << number << endl;
cout << ::number << endl;
return 0;
}
Globally defined variables belong to the global namespace. They will be visible if in any inner scope variables with the same names will not be declared.
#include<iostream>
using namespace std;
static int x=5;
void function1()
{
x=25;
cout<< x;
}
int main()
{
x=10;
cout<< x;
function1();
cout<<x;
}
In the above example, i declare variable x as static int globally.
I declare x=10 in main , now the scope of the variable is in main function , it will be showing x=10.
now i call function1() , and modify the value of x and its scope in function1 is x=25.
when i return back to the main function and output the value of x, i see x=25.
my question is " what is the use of defining a variable as static which has been declared globally..even global variable has a lifetime until the end of the program"
static for global variables/functions means something very different.
If a global variable is static, it means that is not externally linked. It's difficlut to explain in words... so here's an example:
1 2 3 4
//one.cpp
int a;
staticint b;
int c;
1 2 3 4
//two.cpp
externint a;
staticint b;
int c;
Here, 'a' is a variable that exists in both cpp files. Changes made to 'a' in one.cpp will be visible in two.cpp because they both use the same var. That var is instantiated in one.cpp, and the 'extern' keyword in two.cpp tells it to look for a variable that has already been instantiated elsewhere (without instantiating it again)
'b' is declared as static, therefore one.cpp and two.cpp have their own copy of the 'b' variable. Changes made to 'b' in one.cpp will not be visible in two.cpp and vice versa because they are both accessing different vars.
'c' will cause a linker error because the same variable is being instantiated multiple times, and the linker doesn't know which variable you wanted to use.