Static Local variable vs Global variable

What happens inside a function if a static local variable has the same name as a global variable?
How does a static local variable differ from a global variable?

I know static local variables are not destroyed when a function returns but I
don't understand the difference between global variables though.
Static local win, but even its not destroyed when function end the only one that can access static local is the function itself, unlike global that can be accsess by every function in program
closed account (E0p9LyTq)
Global variables are visible to all blocks in your program. Static variables are only visible to the block they are defined in.

Using globals should be avoided.

http://www.cplusplus.com/forum/general/76476/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

int a = 1550;

void myFunc();

int main()
{
   int a = 5;

   // use ::a to reference the global a
   std::cout << "In main:\t" << a << "\t" << ::a << "\n";

   myFunc();

   {
      int a = 455;

      std::cout << "In local block:\t" << a << "\t" << ::a << "\n";
   }

   myFunc();

   return 0;
}

void myFunc()
{
   static int a = 15;

   std::cout << "In myFunc:\t" << a << "\t" << ::a << "\n";
}


In main:        5       1550
In myFunc:      15      1550
In local block: 455     1550
In myFunc:      15      1550
So if they have same name, static local variable shadows global variable right?
closed account (E0p9LyTq)
Local variables always hide globals with the same name, static or not.

Variable visibility: http://www.cplusplus.com/doc/tutorial/namespaces/

Static is generally used so a local block variable in functions so the value remains between calls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

void myFunc();

int main()
{
   myFunc();
   myFunc();
   myFunc();
   myFunc();
   myFunc();

   return 0;
}

void myFunc()
{
   static int a = 0;
   
   std::cout << "In myFunc:\t" << a << "\n";
   
   a += 3;
}


In myFunc:      0
In myFunc:      3
In myFunc:      6
In myFunc:      9
In myFunc:      12
Last edited on
Still you can access global variable by specifying that you need global one:
1
2
3
4
5
6
7
int i; //Global variable

void func()
{
    int i = 2; //Shadows global
    ::i = 5 //Access global variable
}
Topic archived. No new replies allowed.