I'm curious if there's a branchless way to do this, or perhaps just a generally better way:
uint16_t add_with_no_overflow(uint16_t num, uint16_t delta)
{
if (UINT16_MAX - delta < num)
{
return UINT16_MAX;
}
return num + delta;
}
I tried thinking about it with min/max, but even if I try to use (well-defined) uint overflow, the best I can come up with is max(num + delta, num) which would return the original number a if overflown, or the result otherwise.
But I can't think of a way with min/max/clamp to get from this split to the desired behaviour (without branching)
EDIT 2: I checked my specific platform (Xtensa-Esp32). Seems that all versions contain a branch, even simple boolean comparisons (
a > b)So in my case the simplest
ifstatement in the title might be the best choice, even if the different methods are interesting on their own.EDIT 1: Played with ChatGPT on this - after coaxing out the bugs maybe a better implementation?
Thought about this immediately after posting. The magic of rubber ducking!
Implementation with
min/max(not necessarily branchless)