The C Standard explicitly specifies signed integer overflow as having undefined behavior. Yet most CPUs implement signed arithmetics with defined semantics
The answer is actually in your question:
Yet most CPUs implement signed arithmetics with defined semantics
I can't think of a CPU that you can buy today that does not use twos-compliment arithmetic for signed integers, but that wasn't always the case.
The C language was invented in 1972. Back then, IBM 7090 mainframes still existed. Not all computers were twos-compliment.
To have defined the language (and overflow behaviour) around 2s-compliment would have been prejudicial to code generation on machines that weren't.
Furthermore, as it has already been said, specifying that signed overflow is to be UB allows the compiler to produce better code, because it can discount code paths that result from signed overflow, assuming that this will never happen.
If I understand correctly that it's intended to clamp the sum of a and b to 0....INT_MAX without wraparound, I can think of two ways to write this function in a compliant way.
First, the inefficient general case that will work on all cpus:
int sum_max(int a, unsigned char b) {
if (a > std::numeric_limits::max() - b)
return std::numeric_limits::max();
else
return a + b;
}
Second, the surprisingly efficient 2s-compliment specific way:
int sum_max2(int a, unsigned char b) {
unsigned int buffer;
std::memcpy(&buffer, &a, sizeof(a));
buffer += b;
if (buffer > std::numeric_limits::max())
buffer = std::numeric_limits::max();
std::memcpy(&a, &buffer, sizeof(a));
return a;
}
Resulting assembler can be seen here: https://godbolt.org/z/F42IXV