Choose the width before doing the arithmetic
A u8 holds 0 through 255. A u16 holds 0 through 65,535. The 6510 is an eight-bit CPU, so a word occupies two bytes and a word operation can take extra instructions. The survey uses a byte for its four sector numbers and a word for the visit total.
Add in one byte
fn nextByte(value: u8) u8 {
return value + 1;
}
Widen, then add
fn nextWord(value: u8) u16 {
return @as(u16, value) + 1;
}
Both functions take $ff. The first keeps the low eight bits and returns $00. The second widens the input before the operation and returns $0100. Widening a byte that has already wrapped gives $0000. Ordinary arithmetic in ZeroPage retains the low bits of its result width. Standard Zig distinguishes wrapping operators from ordinary arithmetic.
Expect BYTE 00 WORD 0100. The second line separates the high and low bytes by shifting and masking. Hex displays the most significant digit first, while the 6510 representation of a stored word puts its low byte at the smaller address.
Decide which values can change
Use const for a binding such as a record limit and var for a counter that changes. A declaration such as const value = nextWord(0xff); takes its type from the function's return. Add a type to a declaration when the intended width matters, for example var visits: u16 = 0;. A const pointer can still point to mutable storage when its pointee type allows writes.
As you start the survey, keep the state change in one function. Pass a record by value to work on a copy. Pass its address when the caller needs to see the field change. A copied pointer still points to the same bytes. See the record and pointer walkthrough when you add shared data.
Predict the rollover before running it
- Try
0xfeas both inputs. The byte result isFFand the word result is00FF. - Restore
0xff. Imagine a visit total of$00ff. One more visit in the survey should display0100. - Use the language guide when you need signed comparisons, a fixed array, or an optional result. Keep array indexes within the declared length because runtime indexing is unchecked.