What is the function of "(void) (&_min1 == &_min2)" in the min macro in kernel.h? What is the function of "(void) (&_min1 == &_min2)" in the min macro in kernel.h? c c

What is the function of "(void) (&_min1 == &_min2)" in the min macro in kernel.h?


The statement

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

is a guaranteed "no-op". So the only reason it's there is for its side effects.

But the statement has no side effects!

However: it forces the compiler to issue a diagnostic when the types of x and y are not compatible.
Note that testing with _min1 == _min2 would implicitly convert one of the values to the other type.

So, that is what it does. It validates, at compile time, that the types of x and y are compatible.


The code in include/linux/kernel.h refers to this as an "unnecessary" pointer comparison.This is in fact a strict type check, ensuring that the types of x and y are the same.

A type mismatch here will cause a compilation error or warning.


This provides for type checking, equality between pointers shall be between compatible types and gcc will provide a warning for cases where this is not so.

We can see that equality between pointers requires that the pointers be of compatible types from the draft C99 standard section 6.5.9 Equality operators which says:

One of the following shall hold:

and includes:

both operands are pointers to qualified or unqualified versions of compatible types;

and we can find what a compatible type is from section 6.2.7 Compatible type and composite type which says:

Two types have compatible type if their types are the same

This discussion on osnews also covers this and it was inspired by the GCC hacks in the Linux kernel article which has the same code sample. The answer says:

has to do with typechecking.

Making a simple program:

int x = 10; long y = 20;long r = min(x, y);

Gives the following warning: warning: comparison of distinct pointertypes lacks a cast