Difference between local variable VS global variable

Asked

Viewed 767 times

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 mind it makes a difference between being global or local.

1. What is the difference in speed between?

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

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

4. Is there any other significant difference between these two?

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

2 answers

5


  1. What is the difference in speed between?

No significant. They are pre-allocated. Locations need to move a pointer in register, but the cost is close to zero.

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

Yes. Under normal conditions.

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

There’s a specific area of the application that reserves all space for global variables. The locations are in the stack.

  1. Is there any other significant difference between these two?

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

-1

I’ll tell you what I know about this.

Answers:

  1. as far as I know there’s no difference.

  2. yes.

  3. ram memory.

  4. yes! A local variable can only be used within the method it was created, that is, 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.