Variable size/Set: Difference between revisions

Line 928:
Other than arrays and strings, variables are a fixed size. Integers are
four bytes and reals are eight bytes.
 
=={{header|Z80 Assembly}}==
{{trans|6502 Assembly}}
Syntax will vary depending on the assembler and whether your program will run in RAM or ROM.
For programs that execute from RAM such as those that are loaded from a disk, you can use the same syntax that you would use to define constants. When defining bytes as variables or constants, you do not prefix them with a # sign. Only in actual CPU instructions do you need to use a # to prevent the assembler from treating the numeric value as a memory location.
 
Since these are variables, the value given to them (in this case, 0) is the initial value, and can be changed later at runtime. If you don't care what the initial value is, some assemblers allow you to use a "?" where the 0s are.
 
<lang Z80>MyByte:
byte 0 ;most assemblers will also accept DB or DFB
MyWord:
word 0 ;most assemblers will also accept DW or DFW
MyDouble:
dd 0</lang>
 
For programs that are executed solely from ROM, such as video game console cartridges, you won't be able to use the above method. The assembler can often use an <code>enum</code> or <code>rsset</code> directive to sequentially assign labels to a series of consecutive memory locations in the system's RAM.
 
<lang z80>.rsset $C000 ;starting at $C000, the following labels represent sequential memory locations of length ".rs n"
tempByte .rs 1
tempWord .rs 2
tempLong .rs 4</lang>
 
Assemblers that don't have an <code>enum</code> or <code>rsset</code> directive can use the <code>equ</code> directive instead. This method lets you immediately see what each memory location actually is, but it makes it harder to insert a new one without having to redo all the numbering. When loading from an immediate memory location to a 16-bit register pair (e.g. <code>LD HL,($4000)</code>, the "low register" is loaded with the byte stored at the memory location specified by the operand, and the "high register" is loaded with the byte stored at the memory location after that.
<lang Z80>tempByte equ $C000
tempWord equ $C001 ;high byte at $C002
tempLong equ $C003 ;you have to track spacing yourself with this method</lang>
 
While setting a variable's size is easy, getting it isn't possible without knowing it in advance. The CPU does not (and cannot) know the intended size of a variable. There's no enforcement of types whatsoever on the Z80, anything goes. If, for example, you executed <code>LD HL,($4000)</code> and $4000 was <i>intended</i> to be the storage location of an 8-bit value, you'd get the intended value in L and whatever happened to be after it in memory into H. Whether that's a problem or not is up to the programmer, not the CPU.
 
=={{header|zkl}}==
1,489

edits