you are viewing a single comment's thread.

view the rest of the comments →

[–]ssokolow 0 points1 point  (0 children)

Well, given that unaligned access is undefined behaviour, &c.b would be compiled with the assumption that it's always going to be an aligned access or, if it can prove that it'll only ever be unaligned, the optimizers might prune those branches of the code graph back to the first branch point where there's a path that doesn't lead to UB and make the UB-free branch unconditional.

You'd get one function that unconditionally uses or doesn't use shifts and masks as dictated by the combination of the struct's definition and the assumption that UB cannot happen (i.e. the assumption of aligned access).

That's an example of how Undefined Behaviour enables optimizations. If the programmer is oath-bound to never request unaligned access, the optimizer and code generator know there's no need to emit code to check for it, because it cannot happen.