1

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();
}
1
  • 8
    I'm voting to close this question as off-topic because this is a pure software question and better asked (and probably already has an answer) on StackOverflow. Commented May 29, 2019 at 6:49

2 Answers 2

2

There are two things going on here.

  1. 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, ::)

  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Should this be posted as an answer? Perhaps a comment on the question with a link is more appropriate. The question is not about electronics design and should be closed anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.