Ttelmah Guest
|
Re: Global variables versus local |
Posted: Tue Feb 08, 2005 3:58 am |
|
|
Anonymous wrote: | Is it better to use global variables or local ones?
What about the memory - how much memory those variables take?
what I mean is:
Say I define a global variabe 1 byte, it occupys 1 byte in RAM.
What if I define the local variable within the function twice - 2 variables in 2 different functions. will it occupy 2 bytes in RAM or... will it occupy the RAM only when I am in the function?
So how those things work in terms of the memory?
Thank you |
It depends what you want. The 'point' about global variables, is that they allow data to be distributed between routines, without having to go through the complexity of 'passing' the variables between them. However this brings with it the risk of something unexpected modifying a variable. 'Local' variables, 'compartmentalise' the data access, to avoid anything else changing the data, while a routine is running, and when the memory is not being used, allowing other things that are seperated in 'time', to use the same space.
If (for instance), you have a global variable 'fred', and it is used in a routine, and also accessed in an interrupt, the potential exists for the data to be changed at a point inside 'fred', without being expected. Hence if fred want's to do something with this data 'stable', it would need to save a copy, or disable interrupts.
If you have two routines 'tom', and 'harry', and these have local variables used in them, and they are called from main, one after the other, then the same memory area can be used for both sets of variables. However, if 'tom', itself calls 'harry', then the data space cannot be reused, since it is still 'in use' in tom, when harry is executing.
Also a 'local' variable, that is 'static', has the memory 'costs' of a global variable, but gains the protection, that it cannot be changed by anything, even while the subroutine is not being executed.
Now the 'protection', is somewhat fragmentary on the PIC (you don't have the sophistication of a memory manager, which can actually 'lock' pages to prevent access), and only applies to obvious accesses using the variable names (you can for instance overwrite the contents of a variable, using assembler, or the memory 'pointer' ability.
The advantage of 'local' variables, is that they save space, which on a chip like the PIC, can be essential. If you think of how many locations are used for simple 'local' values, like counters, and temporary stores, local variables are a tidy way of dealing with these.
'Better', well the answer will depend on what you are actually doing. Most users probably end up using a 'mix', and declaring local variables, that are initialised when the routine starts, for most things, and add a few 'global' variables, for values from interrupt driven routines (like serial buffers etc.). This gives efficient use of the limited space.
Best Wishes |
|