Hi,
In my C code, I need to assign a lot of values. Like this: a1,a2,... are variables as char. v1,v2...,w1,w2...y1,y2 are constant (like 0x00, 0x01, ...etc)
if (i==0){ a1 = v1; a2 = v2; ... a50=v50; } else if (i==2){ a1 = w1; a2 = w2; ... a50=w50; } else if (i==3){ a1 = y1; a2 = y2; ... a50=y50; } else { }
I would like to minimize the code memory usage as possible. Which coding style or method is suggested to implement it ? Should I declare "array" or use " #define " ? Please kindly provide suggestions. Thanks a lot!
#define doesn't remove any assigns.
Definitely consider using arrays. Just remember that 8051 chips aren't exactly loving work with arrays because a bit of lack of addressing modes.
Another thing - should you really assign 50 values? Or have change one pointer to point to a struct/array containing the specific set of 50 values? Is it real variable variables or do you use them as constants, where it would be possible to have them stored in code memory?
I have three groups-(v1,...v50), (w1,...w50) and (y1,...y50), each group has 50 constant values. By if-else condition, it needs to choose one group to assign the constant values to "a" variables(a1,a2,...a50).
Instead of one by one assignment, I want to know if there is any other better coding method that is more efficient and with smaller code or data memory size usage.
Please provide some suggestions. Thanks a lot!
I assume I'm doing your homework, anyway...
unsigned char xdata a [50]; const unsigned char code v [50] = {1,1,1,1,1,1,1,1 /* and so on up to all 50 */ }; const unsigned char code w [50] = {2,2,2,2,2,2,2,2 /* and so on up to all 50 */ }; const unsigned char code y [50] = {3,3,3,3,3,3,3,3 /* and so on up to all 50 */ }; void init_a (unsigned variant) { switch(variant) { case 0: memcpy(a,v,sizeof(a)); break; case 2: memcpy(a,v,sizeof(a)); break; case 3: memcpy(a,v,sizeof(a)); break; default: /* cry for help */ break; } } /* Or maybe this? */ const unsigned char code * a2; void init_a2 (unsigned variant) { switch(variant) { case 0: a2 = v; break; case 2: a2 = w; break; case 3: a2 = y; break; default: /* cry for help */ break; } }
"needs to choose one group to assign the constant values"
Does it really need to assign all the individual values?
Can't you just have a pointer and set that to point to the appropriate set of constants?
How about maybe respond with some answer to: "Another thing - should you really assign 50 values? Or have change one pointer to point to a struct/array containing the specific set of 50 values? Is it real variable variables or do you use them as constants, where it would be possible to have them stored in code memory?"
There are no reason to waste RAM if we are talking about constants.
View all questions in Keil forum