So this seems easy but either I'm missing something or... there is no way to do it?..
First try:
unsigned abs(int value) { return value < 0 ? -value : value; }
Nope, "-value" is an UB. This is detected by clang -fsanitize and is generally unsafe in the face of aggressive optimizations (although I really hope no sane compiler abuses this).
Ok. Let's cast to unsigned!
unsigned abs(int value) { return value < 0 ? -unsigned(value) : unsigned(value); }
Nope, this results in C4146 warning in MSVC. Additionally due to definition of unary minus on unsigned values I think this assumes a two-complement integer format for signed integers.
Ok...
unsigned abs(int value) { return value < 0 ? ~unsigned(value) + 1 : unsigned(value); }
This does not seem to generate any warnings or undefined behaviors, but of course only works for two-complement integers. Also, it's kinda obscure - needs a comment that explains why this is not using something straightforward...
Is it actually possible to implement an aforementioned function without triggering UBs or relying on the integer representation? Please tell me the answer is "yes" before I lose all remaining hope in C.