datenwolf February 2016

Desired effect of value-discarded comparision of GCC anonymous function variables' addresses

The Linux kernel defines a number of helper macros for type neutral numeric operations. Namely the macros min and max are defined as (in include/linux/kernel.h)

#ifndef max
#define max(x, y) ({ \
        typeof(x) _max1 = (x); \
        typeof(y) _max2 = (y); \
        (void) (&_max1 == &_max2); \
        _max1 > _max2 ? _max1 : _max2; })
#endif
#ifndef min
#define min(x, y) ({ \
        typeof(x) _min1 = (x); \
        typeof(y) _min2 = (y); \
        (void) (&_min1 == &_min2); \
        _min1 < _min2 ? _min1 : _min2; })
#endif

When expanded they produce anonymous functions that perform the operation type neutral and in-expression-assigment safe way (using GCC anonymous functions). So far so good. What surprised me is the second to last expression produced by these macros:

   (void) (&_min1 == &_min2);

The addresses of the temporary variables defined within the scope of the anonymous function are compared and the result then discarded; the (void) cast preventing any warnings to show up.

I wonder what the desired side effect of this is? Naively I'd expect this to get optimized away, since it has no side effects (at least none I am aware of).

Answers


Olaf February 2016

The compiler will complain for the == if both variables don't have the same type. So I suspect this is to ensure the values really can be compared.

Try:

int i;
char *p;
(void)min(i, p);

And yes, the operation will be optimised away with any optimisation level other than -O0.

Post Status

Asked in February 2016
Viewed 3,776 times
Voted 11
Answered 1 times

Search




Leave an answer