top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between defining a variable as static vs global?

+3 votes
607 views
What is the difference between defining a variable as static vs global?
posted Nov 12, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

A static variable has a file scope if variable is outside of the function means it can be accessed into the file in which it is defined. Where is a global variable can be accessed in all the files of a executable.

File a.c
static int a;
int b;

File b.c 
// In this file we can access b but not a.

When a static variable is defined inside a function that mean this variable i=has a function scope and would retain the value even after the control leaves the function and the same function is called again then last stored value can be accessed.

func()
{
  static int a=5;
  a++;
  printf("%d\n", a)
}
on the first call value will be printed as 6 and next function call it would be 7.
answer Nov 12, 2013 by Sheetal Chauhan
+1 vote

Global : Accessible across multiple files.
Static outside functions : Accessible anywhere in the current file.
Static inside functions : Accessible only with in the function then why not AUTO, because AUTO variable wont retain value on multiple calls..

answer Nov 12, 2013 by sivanraj
Similar Questions
0 votes
#define MY_STRUCT
typedef struct{ 
...
... 
} my_struct;

Above code is giving me error (MY_STRUCT) is not working as expected, Looks that some silly mistake, please point out as I have wasted many hours?

Sorry for hiding my identity?

...