【问题标题】:What is 'typeof((fifo) + 1)' means from linux/kfifo.h file?linux/kfifo.h 文件中的“typeof((fifo) + 1)”是什么意思?
【发布时间】: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


【解决方案1】:

@Wonil 你的第一个假设是正确的。此构造用于检查是否将指针用作参数。

当给定一个普通结构时,表达式将引发编译器错误,因为结构用于一元 + 和 int。

当给定一个指针时,二进制 + 将给它加 1,它仍然是指向相同类型的指针,并且表达式在语法上是正确的。

【讨论】:

  • 我猜到原因是这样的。这种技巧很有用,但我有点希望在头文件中有关于它的注释,因为它的意图并不明显。
猜你喜欢
  • 1970-01-01
  • 2019-12-26
  • 2019-08-18
  • 2014-09-15
  • 2020-04-19
  • 1970-01-01
  • 2010-12-28
  • 2020-03-24
相关资源
最近更新 更多