Difference between local variable VS global variable

4

In my micro controller classes the variables are always defined globally and very rarely locally and I would like to know why, because in my head it makes a difference between being global or local.

1.

2. Both the local variable and the global variable occupy the same space     memory?

3. Where is the global variable stored in memory? And the variable     local?

4. Is there any significant difference between these two?

Highlight that I'm not programming in pure Arduino, I'm programming in C and then I put it in the Arduino microcontroller.

    
asked by anonymous 28.09.2018 / 16:49

2 answers

5
  
  • What is the difference in speed between one and another?
  •   

    None significant. They are preallocated. Locals need to tinker with a pointer in register, but the cost is close to zero.

      
  • Both the local variable and the global variable occupy the same memory space?
  •   

    Yes. Under normal conditions.

      
  • Where is the global variable stored in memory? What about the local variable?
  •   

    There is a application-specific area that reserves all space for global variables . The places are in the stack .

      
  • Is there any significant difference between these two?
  •   

    The lifetime . And of course scope too, but in context is less important. For code readability global variables are considered to be bad precisely by scope. In Arduino there are no major problems with the global ones because access is never shared by threads (but if one day has some form of competition, it happens to be a problem.)

        
    28.09.2018 / 17:00
    -1

    I'll tell you what I know about this.

    Answers:

  • As far as I know, there's no difference.

  • Yes.

  • RAM.

  • Yes! A local variable can only be used within the method it was created, ie if you try to use this local variable in another method, you will not be able to.

  • A Global variable can be viewed anywhere in the system.

        
    28.09.2018 / 16:59