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!
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; } }
Hi Jane,
Thanks for your reply.
By Keil C51 v4 compiler, it shows your method 2 has smaller code memory usage than method 1.
In your method 2, about the pointer *a2: Is *a2 being an array that consists 50 elements and can be assigned the values from v, w and y?
The value assignment is one by one mapping ? Like a2[0] <-> v[0], a2[1] <-> v[1], ..., a2[50] <-> v[50]...etc ?
Thanks!
"Is *a2 being an array that consists 50 elements"
No!
a2 is a pointer which points to the start of one of the constant arrays - so there is no copying of the data!
Of course, in 'C', arrays & pointers are very closely related; eg, the indexing operator [] can be applied to a pointer:
*a2 dereferences the pointer; ie it gives the pointed-to item - which is the 1st element of one of the constant arrays.
a2[0] is equivalent to *a2.
a2[1] gives the second element of one of the constant arrays.
etc, etc,...
This is 'C' textbook stuff - nothing specific to the 8051, Keil, C51, or embedded.
c-faq.com/.../index.html