Re: [PATCH v3 1/4] iio: prepare iio_format_value to handle higher-precision IIO_VAL_DECIMAL64_* formats

From: Andy Shevchenko

Date: Wed Oct 28 2026 - 04:11:49 EST


On Tue, Oct 27, 2026 at 03:56:35PM -0300, Rodrigo Alencar wrote:
> On 26/10/26 11:51, Victor Chernyakin wrote:

+Cc: David Laight

...

> > +/*
> > + * Regular abs(LLONG_MIN) causes signed overflow, which is undefined
> > + * behavior. This variant avoids that by performing the computation in an
> > + * unsigned type, for which negation is always well-defined.
> > + */
> > +static inline u64 abs_s64_no_overflow(s64 x)
> > +{
> > + return x < 0 ? -(u64)x : (u64)x;
> > +}
>
> I think I've seen Andy doing mentions to a needed 'safe' abs() a couple of times.
> Don't we have something in the tree already? if not, Why not adding a
> 'unsigned' abs function to math.h? something like:

Or maybe something clever using the s64/u64 domain for all.
Let's gather David Laight's opinion.

> /**
> * uabs - return absolute value of an argument as an unsigned type
> * @x: the value.
> *
> * Unlike abs(), the result is well defined when @x is the minimum value of
> * a signed type, since the negation is done in the unsigned domain.
> *
> * Return: an absolute value of @x, as the unsigned counterpart of its type.
> */
> #define uabs(x) __uabs_choose_expr(x, long long, \
> __uabs_choose_expr(x, long, \
> __uabs_choose_expr(x, int, \
> __uabs_choose_expr(x, short, \
> __uabs_choose_expr(x, char, \
> __builtin_choose_expr( \
> __builtin_types_compatible_p(typeof(x), char), \
> ({ signed char __x = (x); \
> (unsigned char)(__x < 0 ? -(unsigned char)__x : \
> (unsigned char)__x); }), \
> ((void)0)))))))
>
> #define __uabs_choose_expr(x, type, other) __builtin_choose_expr( \
> __builtin_types_compatible_p(typeof(x), signed type) || \
> __builtin_types_compatible_p(typeof(x), unsigned type), \
> ({ signed type __x = (x); \
> (unsigned type)(__x < 0 ? -(unsigned type)__x : \
> (unsigned type)__x); }), other)

--
With Best Regards,
Andy Shevchenko