这是什么意思? return 函数()

What does this mean? return func()

在Linux内核源代码中,我找到了这个。

int         (*check_fb)(struct device *, struct fb_info *);
...
...
...
static int pwm_backlight_check_fb(struct backlight_device *bl,
                  struct fb_info *info)
{
    struct pwm_bl_data *pb = bl_get_data(bl);

    //something more

    return !pb->check_fb || pb->check_fb(pb->dev, info);
}

我不明白最后的return 语句,它是什么意思?我们可以 return 一个函数吗?通常我们return一个值。

不,它不是 returning 函数 本身。其实是

  • 正在检查函数指针的非 NULL 值。

    • 如果没有NULL
      1. 使用函数指针调用函数
      2. return调用函数的 return 值。
    • 如果NULL
      1. return !NULL (1).

引用C11标准,第6.8.6.4章,return声明

If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression.

在 C++ 中,|| 运算符是一个短路运算符,这意味着,如果第一个参数为真,它甚至不会 计算 第二个,因为true || anything 始终为真。

因此声明:

return !pb->check_fb || pb->check_fb(pb->dev, info);

是一种检查非 NULL 函数指针并使用它来决定当前 return 值的简便方法:

  • 如果函数指针是NULL,只需return!NULL,就会得到1.

  • 如果它是 not NULL,!pb->check_fb 将计算为 0,因此您必须调用该函数,并使用无论 returns,作为这个函数的return值。

所以它实际上等同于:

if (pb->check_fb == 0)
    return 1;
return pb->check_fb (pb->dev, info);

现在我说 "effectively" 但实际 returned 可能与您看到的和我上面的最终代码片段略有不同。但是,如果您将它们视为 true/false 值,效果是相同的。

从技术上讲,最后一行应该是:

return 0 || pb->check_fb (pb->dev, info);

具有完全相同的 return 值。