Variables: Difference between revisions

Content added Content deleted
m (→‎{{header|Diego}}: various syntax, spelling corrections)
Line 3,213: Line 3,213:


Here, <code>print_heads</code> and <code>print_tails</code> take, by type, a coin, which could be either heads or tails, but this code has used the variable instantiation system to insist that they can each only accept one particular value. If you take this code and change the main/2 so that it instead tries to call <code>print_tails(N, !IO)</code>, you'll get a compile-time error. A practical use of this is to avoid having to handle impossible (but well-typed) cases.
Here, <code>print_heads</code> and <code>print_tails</code> take, by type, a coin, which could be either heads or tails, but this code has used the variable instantiation system to insist that they can each only accept one particular value. If you take this code and change the main/2 so that it instead tries to call <code>print_tails(N, !IO)</code>, you'll get a compile-time error. A practical use of this is to avoid having to handle impossible (but well-typed) cases.

=={{header|MIPS Assembly}}==
Depending on your assembler, variables are either declared in a <code>.data</code> section, or you can use <code>.equ</code> or <code>.definelabel</code> directives to name a specific memory offset. The CPU doesn't (and can't) know the variable's size at runtime, so you'll have to maintain that by using the instructions that operate at the desired length.

<lang mips>foo equ 0x100
bar equ foo+1
;it's heavily implied that "foo" is one byte, otherwise, why would you label this? But you should always comment your variables.</lang>

Initialization is done by setting the variable equal to a value. For variables that live entirely in a register, this is very simple:
<lang mips>li $t0,5 ;load the register $t0 with the value 5.</lang>

For memory, this is a bit harder.
<lang mips>.definelabel USER_RAM,0xA0000000
foo equ 0x100 ;represents an offset from USER_RAM. Indexed offsetting can only be done at compile time in MIPS.

la $t0,USER_RAM
nop ;load delay slot ($t0 might not be ready by the time the load occurs)
lbu $t1,foo($t0) ;load the unsigned byte from memory address 0xA0000100</lang>

Variables have no scope, and there is no enforcement of data types. There's nothing stopping you from loading a 32-bit word from an offset that was intended to store a byte. Do so at your own risk.


=={{header|Modula-3}}==
=={{header|Modula-3}}==