Reputation: 75
In C both static local variable and static global variable with same name declaration are done in same file. They both are stored in data segment memory.
When I compile code why it is not throwing error?
In same memory 2 variable with same name can be stored?
Please find code below
#include <stdio.h>
static int x = 0;
void call()
{
printf("Adress of gloabl static =%p",&x);
}
int main()
{
static int x = 0;
printf("Adress of local static =%p",&x);
call();
}
Upvotes: 1
Views: 1723
Reputation: 935
There are two things going on here.
Variable scopes.
There is a public x
and a local x
in main. Say x
and main:x
. C defaults to the local one. As far as I am aware, C offers no method to access the global one when the reference has been overridden by a local one. (C++ does, ::)
Different meaning for the static
keyword.
2.1 The static
keyword in global scope means the object x
may not be referenced from anywhere except this file. Even with extern
it will throw you an error. This is great, as it prevents unintended usage of "private" objects in a module.
2.2 The static
keyword in local scope means the object x
will be allocated once, permanently. Any instance of main()
uses the same x
.
Like a global, while only being accessible from within the scope. x
will persist even if you exit main. This also means you cannot use an initializer, it will error on the above if not 0. Since when should it do the initialization?
Standard specifies all static objects in local scope shall be initialized.
Local statics are great if you need to carry over data to the next time the functions runs, especially with interrupts, but do not want the data to be public.
Static is a great keyword to do basic data hiding for multi file microcontroller programs. Keeping your code clean and not littered with globals.
Upvotes: 2
Reputation:
This programming question has already been answered in stackoverflow as this has nothing to do with electronics.
That said, local variables have precedence and will shadow a global variable. It is perfectly valid to do so. Some compilers might warn about this. If this bothers you, don't use global and local variables with same name then.
Upvotes: 0