@alignCast(@ptrCast(x)) or @ptrCast(@alignCast(x))?

I see both patterns in the zig compiler and standard library repo. Claude (AI chatbot) suggests the difference is significant but fails to convince me. It feels most natural to alignCast last, but are both forms equivalent?

(The need for pointer casting arises when implementing interfaces using *anyopaque).

1 Like

I don’t think there is a meaningful difference, but I could be wrong. I believe the calls are orthogonal. They each do a different, but complimentary, job.

1 Like

There is no difference.

@ptrCast reinterprets the child type of the pointer, this translates to nothing at runtime, as types are only in zig land.
@alignCast changes the alignment of the pointer, this may change the address that the pointer is pointing at if it isn’t already aligned, since in zig alignment is part of pointer types this may be optimised out.

The order they are done in has no effect on the result.

You can leave one or the other off if your pointer already meets one or the other requirements.

5 Likes

I’m glad you brought this up because I thought that zig fmt would change these to a canonical ordering, but I checked just now and that did not happen.

bug report

11 Likes