linux/kernel.h (&_x == &_y); why

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Anybody here understand the '"unnecessary" pointer comparison' of the
min/max of linux/kernel.h?

Are we trusting gcc to disregard that sourceline?  If yes then why
bother?  Why not omit that sourceline?

Pat LaVarre

---

http://lwn.net/Articles/driver-porting/

Miscellaneous changes ...
http://lwn.net/Articles/22196/

...
The min() and max() macros

A common step in the development of most C programmers, shortly after
they learn to include stdio.h seems to be the definition of macros like:

    #define max(a,b) ((a) > (b) ? (a) : (b))

In 2.5, it was noted that a number of kernel developers had seemingly
not moved beyond that stage, and there was an unbelievable number of
min() and max() definitions sprinkled throughout the kernel source.
These definitions were not only redundant - they were unsafe. A max()
macro as defined above has the usual problem with side effects; it also
is not type-safe, especially when signed and unsigned values are used. 

Linus initially added his own definition of min() and max() which added
a third argument - an explicit type. That change upset people badly
enough that some put substantial amounts of time into developing
two-argument versions that are type and side-effect safe. The result now
lives in <linux/kernel.h>, and should be used in preference to any
locally-defined version.
...

http://lxr.linux.no/source/include/linux/kernel.h?v=2.6.0-test7#L157

...
157 /*
158  * min()/max() macros that also do
159  * strict type-checking.. See the
160  * "unnecessary" pointer comparison.
161  */
162 #define min(x,y) ({ \
163         const typeof(x) _x = (x);       \
164         const typeof(y) _y = (y);       \
165         (void) (&_x == &_y);            \
166         _x < _y ? _x : _y; })
167 
168 #define max(x,y) ({ \
169         const typeof(x) _x = (x);       \
170         const typeof(y) _y = (y);       \
171         (void) (&_x == &_y);            \
172         _x > _y ? _x : _y; })
...


--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/


[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux