#is there any resources to know about alignment concept
1 messages · Page 1 of 1 (latest)
alignment of a pointer is simply the value by which a pointer's integer value is divisible
ie
var foo: u8 align(16) = 0;
const bar: *align(16) u8 = &foo;
assert(@intFromPtr(foo) % 16 == 0);
if by "how do I change alignment" you mean "how do I change the alignment of a pointer", the answer is that it's not actually possible. Alignment is a descriptive property. You can cast a pointer type to a higher alignment by asserting that the represented value is in fact divisible by the higher value, but whether or not it is is as static as 3 % 4 == 3
the reason it's represented in the type system the way it is is because the divisibility of a pointer actually represents a physical characteristic of the address on the hardware, which is important for working with CPUs - it allows usage of instructions that operate on data that aligns with certain physical lanes
Alignment exists because computers generally don't actually grab a single byte at a time from memory. You can end up with some data that could fit in a single read, but is stretched across multiple reads because it's not aligned-- this will slow down your program and some processors may just not support it. I liked this article on the topic: https://developer.ibm.com/articles/pa-dalign/
IBM Developer is your one-stop location for getting hands-on training and learning in-demand skills on relevant technologies such as generative AI, data science, AI, and open source.