| ||||||||
Technical Support Support Resources Product Information | C51: CORRECTLY DECLARING VARIABLES WITH MEMORY SPACESInformation in this article applies to:
QUESTIONWhen I declare a variable with a memory space, what format should I use? [Data type] [Memory Space] Variable_name or [Memory space] [Data type] Variable_name ANSWEREither way is acceptable (see below for more information). For example: int data var; data int var; both declare an integer in the data memory space. The place to be careful is in complex declarations involving pointers where multiple memory spaces may be required. For example: data int *p; is a generic pointer to an integer. The integer may be in any memory space, but the pointer is stored in the data memory space. int data *p; is a memory-specific pointer to an integer in the data memory space. The pointer is stored in the default memory space. xdata int data *p; is a pointer (stored in xdata) that points to an integer (stored in data). Note that the older method of declaring variables: [Memory space] [Data type] Variable_name may not be supported in future versions of the compiler. For this reason, [Data type] [Memory Space] Variable_name is the preferred method of declaring variables and [Data type] [Data type Memory Space] * [Variable Memory Space] Variable_name is the preferred method of declaring pointers. For example: int data * xdata p; is a pointer (stored in xdata) that points to an integer (stored in data) using the new format. The following example code:
void main (void)
{
int data * xdata p;
p = 0x08;
*p = 0xAA;
while (1);
}
when compiled, yields the following:
; FUNCTION main (BEGIN)
; SOURCE LINE # 5
0000 900000 R MOV DPTR,#p
0003 7408 MOV A,#08H
0005 F0 MOVX @DPTR,A
; SOURCE LINE # 7
0006 E0 MOVX A,@DPTR
0007 F8 MOV R0,A
0008 7600 MOV @R0,#00H
000A 08 INC R0
000B 76AA MOV @R0,#0AAH
000D ?C0001:
; SOURCE LINE # 9
000D 80FE SJMP ?C0001
; FUNCTION main (END)
As you can see, the compiler loads the address of p (the pointer) into the DPTR register and uses the MOVX instruction to access p. SEE ALSO
Last Reviewed: Wednesday, March 15, 2006 | |||||||
| ||||||||