#alignment of array
1 messages · Page 1 of 1 (latest)
var foo: [32]byte align(8) = undefined;
Thanks.
o7
silly question but what does the alignment change ?
The spacing between two elements of the array
but why would there be a spacing between two elements of an array ?
and from the doc
fn noop1() align(1) void {}
fn noop4() align(4) void {}
what does it change here, why would I need this ?
(I am asking that in a curious way xD like want to understand)
CPUs are often faster if e.g. the addresses of a u64 only differ in the last 3 bits. This means u64 have an alignment of 8 (if you don't change it). This means every pointer to a u8 is divisble by 8. Otherwise the CPU may need to load more values and combine them, which takes longer. This means the struct struct { a: u64, b: u32, } has a size of 8+4=12 bytes, but in an array between two such elements there has to be a spacing of 16, to keep a aligned.
There are some specifc usecases where changing the alignment is sometimes a good idea. If you receive a blob of data with no alignment and want to read a u64, you can read from this *align(1) u8, but this is, how I explained slower, than reading from a * u8.
Another very specific usecase I once had, was GPU programming. Some 3 value Vectors had be be aligned as if they had 4 values.
I am not sure about this, but I think the function pointer will be divisible by 1 or 4.
Often we use u128 (well, actually @Vector(x,y) such that a simd register size) for Vectors of 3 32 bits values
okay yeah I maybe see, is it similar to packing data in a packed struct ?
Yes, having pointers with less than normal alignement is similar to having packed structs.
When you look at test_misaligned_pointer.zig in the docs, you can even see, that the error logs say, that the alignment of a pointer to a member of a packed struct differs to the alignment of a normal pointer of the same type.
IIUC this changes the alignment of all elements of the array? Is there a way to change the alignment only of the array itself? E.g. have array of u8 aligned on a 4 byte boundary? IIUC one can specify this for a variable:
var x align(4): .....
but is there a way to specify this for a type?
it aligns the array, not each individual item
the type of &foo given var foo: [32]u8 align(8) is *align(8) [32]u8 - an 8-byte-aligned pointer to an array of 32 normally-aligned u8s
How would I request that each individual item of the array is aligned instead?