Is it fine to declare a global variable as auto. for example
auto int i;
static int j;
int main()
{
...
return 0;
}
Is it fine to declare a global variable as auto. for example
auto int i;
static int j;
int main()
{
...
return 0;
}
Based on this explanation of auto:
http://msdn.microsoft.com/en-us/library/6k3ybftz%28VS.80%29.aspx
It says that auto variables are scope-limited, and their address is not constant. Since globals have neither of these properties, it wouldn't make sense for a global to be auto.
Hi
The meaning of 'auto' in C is simply a variable that is a local variable. So it is totally contradictory to say you would like to declare a global variable as a local variable.
I think you are talking about having a localised global. If you would like to declare a variable that is local to the .c file you are working in, and you don't want it to be accessible outside the c file, but you would like for it to be accessible by all functions in that file, you should declare it as a static variable, like you have done for the variable j.
Therefore you would have something like the following in example.c:
static int i; //localised global within the file example.c
static int j; //not accessible outside the .c file, but accessible by all functions within this file
int main()
{
//do something with i or j here.
i = 0 ;
j = 1 ;
}
void checkFunction()
{
//you can also access j here.
j = j+ 5;
}
I guess I should add that there are multiple ways you to use the keyword static for a variable.
The one that you might be familiar with is:
1) Declaring a variable static within a function - this ensures the variable retains its value between
function invocations.
The second one ...
2) Declaring a variable as static within a module (or a .c file) - this is what I have described
above. This ensures a variable is localised within that module or .c file, but it is global so that
it can be used by any of the functions defined in that particular file. Hence the name localised
global.
However, it will not be accessible outside that .c file.
Why haven't you tried compiling the code snippet in your question? If you had, you would know by now that it gives a compiler error. In gcc:
foo.c:3: error: file-scope declaration of 'x' specifies 'auto'
So I guess the answer tyo your question is "no, it's not fine".
No, it is not possible. The reason is that global variables are in a specific data segment (along with static variables declared inside the functions) initialized to zero all at once before main() is called.