mjcoury wrote:
Yes that makes sense... am I correct in stating that a #define replaces values at the time of compile so would consume even less space since it would not require any storage at all?
Oh, it still requires storage. It just stores it in Flash amongst the code. The #define statement is a pre-compiler directive. Technically, any line that begins with a # is something for the pre-compiler to act on. The pre-compiler will replace all instances of the defined token with its definition. So doing this:
#define DELAY 40
for (i=0;i<DELAY;i++) {
for (j=0;j<DELAY;j++) {
asm NOP;
}
}
is exactly the same as this (as far as the compiler is concerned):
for (i=0;i<40;i++) {
for (j=0;j<40;j++) {
asm NOP;
}
}
When the compiler generates machine code, it will see the number 40 and use the immediate addressing mode in order to compare with the accumulator. The number 40 will be stored in the code as many times as you are referencing it. In this case it is twice. Here is the assembly generated by CodeWarrior Ver5:
Code:
7: char i,j; 8: for (i=0;i<DELAY;i++) { 0002 95 [2] TSX 0003 7f [2] CLR ,X 0004 [5] L4: 9: for (j=0;j<DELAY;j++) { 0004 6f01 [3] CLR 1,X 0006 [5] L6: 10: asm NOP; 0006 9d [1] NOP 0007 6c01 [4] INC 1,X 0009 e601 [3] LDA 1,X 000b a128 [2] CMP #40 ;<---- notice opcode a1 and immediate constant 40, which is $28 in hexadecimal 000d 25f7 [3] BCS L6 000f 7c [3] INC ,X 0010 f6 [2] LDA ,X 0011 a128 [2] CMP #40 ;<---- and here it is again. 0013 25ef [3] BCS L4 11: } 12: } 13: }
It's really up to the compiler though, how to handle it. I tried defining a 'const char' global variable and CodeWarrior generated exactly the same code as above. So either way you do it, the compiler has the final say - but you can switch off certain optimizations if you want.