Hacker News new | ask | show | jobs
by zrm 199 days ago
> If you use `&` instead of `&&` (so that all array elements are accessed unconditionally), the optimization will happen

But then you're accessing four elements of a string that could have a strlen of less than 3. If the strlen is 1 then the short circuit case saves you because s[1] will be '\0' instead of 'e' and then you don't access elements past the end of the string. The "optimized" version is UB for short strings.

2 comments

Yes, so that's why the compiler can't and doesn't emit the optimized version if you write the short circuited version - because it behaves differently for short strings.
UB doesn't exist in the processor (it does, but not here). If the compiler knows the pointer is aligned it can do the transformation.
For the compiler to know the pointer is aligned it would have to actually be aligned and there is no guarantee that it is.