【发布时间】:2013-04-24 15:46:09
【问题描述】:
我从 Linux 内核源代码中的 linux/kfifo.h 文件中找到了以下代码。
/**
* kfifo_init - initialize a fifo using a preallocated buffer
* @fifo: the fifo to assign the buffer
* @buffer: the preallocated buffer to be used
* @size: the size of the internal buffer, this have to be a power of 2
*
* This macro initialize a fifo using a preallocated buffer.
*
* The numer of elements will be rounded-up to a power of 2.
* Return 0 if no error, otherwise an error code.
*/
#define kfifo_init(fifo, buffer, size) \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
__is_kfifo_ptr(__tmp) ? \
__kfifo_init(__kfifo, buffer, size, sizeof(*__tmp->type)) : \
-EINVAL; \
})
从这段代码中,“typeof((fifo) + 1)”是什么意思? 为什么不使用'typeof(fifo) __tmpl = (fifo);'
【问题讨论】:
-
好的。多花5分钟后,我明白为什么了。 kfifo_init 和其他与 kfifo 相关的宏需要第一个参数作为指向 kfifo 结构的指针。如果这个宏的用户不小心将普通的 kfifo 结构用于第一个参数,这将因为 typeof 中的 +1 而导致编译错误。
-
我也很好奇。 '+1' 告诉 gcc 采用 '1' (int) 的类型或 'fifo' 的类型,无论哪个需要被提升。看看这篇文章:stackoverflow.com/questions/4436889/what-is-typeofc-1-in-c
-
有趣,@PeterL。链接的解释与我想的完全不同。需要考虑更多。
标签: gcc linux-kernel