I've not come across this in any compiler I've used. Care to name and shame
...
MikroC does this. Any local vars declared inside functions are just allocated to a fixed RAM location in the PIC.
I imagine this is common with C compilers for microcontrollers? What would be the alternative? The compiler would have to allocate some area inside the PIC RAM for all the local vars to share (how much?) then ensure that there is no possibility of overlaps during runtime where two functions might both use the same RAM location for their local variable. Then somehow get the PIC to dynamically assign the var to any free location (with bank switching) when the PIC is running? That sounds like code bloat.
Alternatively it could try and work out which functions would be in use when others cannot be in use, and just overload a few local vars to the same location? That sounds like a reduction in RAM savings and is still a level of complexity and possibility things may go wrong. Understanding that in a PIC the hardware registers and PORT pins might be the thing that determine if a function can get called, how does the compiler know whether any function will get called at what points?
And if it trys to err on the side of caution with each variable (not knowing what functions may be called)... it gets closer and closer to that model of just assigning one global RAM location to each local var (which my compiler does).
Have you checked your compiler? Make a few functions and see if the compiler allocates a RAM location for each local variable, then maybe try calling those functions based on what a PORT pin does.
MisterT said:
re "for (int i=1; i<= 6; i++)"...
Usually compilers are very good at optimizing loops like that.
Really? I've never tried doing;
Code:
for(int i=0; i<1000; i++) bigbuffer[i] = 0;
for(int i=0; i<100; i++) littlebuffer[i] = 0;
But that just looks like poor programming practice to me compared to re-using a global i var.
MisterT said:
If you use global re-usable variable for "int i", you better be careful not to use the same "i" in interrupts etc.
Absolutely agreed! But I would add that with interrupts etc on microcontrollers the user should be well aware of issues with all global vars not just re-usable ones, even variables used to move data in/out of the interrupt can have issues, especially multibyte vars.