bool add_will_overflow(int32_t a, int32_t b) {
uint32_t c = (uint32_t)a + (uint32_t)b;
return (((uint32_t)a ^ c) & ((uint32_t)b ^ c)) >> 31;
}
That produces the following assembly (see Godbolt[2]): lea edx, [rdi+rsi]
mov eax, edi
xor eax, edx
xor esi, edx
and eax, esi
shr eax, 31
ret
In Rust, you can write a.checked_add(b).is_none() which produces the following assembly[3]: add edi, esi
seto al
ret
A fun fact about this code: the overflow flag which is set by the add instruction and then harvested dates back at least to the 8080 (almost 50 years ago) and is not present in vanilla ARM. However, Apple Silicon has it as an extension, to make life easier for Rosetta 2 binary translation[4]. So when you do get to use this shorter code sequence, be thankful of the effort that chip designers put in to make it execute efficiently.I expect the C23 built-in functions will perform as well as Rust here, which is a win both for ergonomics (you can't really consider the current state of "will a+b overflow" to be discoverable) and performance.
[1]: https://mastodon.online/@raph/109535617953722719
[2]: https://godbolt.org/z/17zMsWjYv