简体   繁体   English

这是什么意思? 返回函数()

[英]What does this mean? return func()

In Linux kernel source code, I found this.在 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);
}

I don't understand the last return statement, what does it mean?没看懂最后的return语句是什么意思? And can we return a function?我们可以返回一个函数吗? Usually we return a value.通常我们返回一个值。

No, it is not returning a function itself.不,它本身不返回函数 It is actually它实际上是

  • Checking for non- NULL value of the function pointer.检查函数指针的非NULL值。

    • If not NULL如果不是NULL
      1. Calling the function using the function pointer使用函数指针调用函数
      2. returning the return value of the called function.返回被调用函数的return值。
    • if NULL如果为NULL
      1. return !NULL ( 1 ).返回!NULL ( 1 )。

Quoting C11 standard, chapter 6.8.6.4, The return statement引用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.如果执行带有表达式的return语句,则表达式的值将作为函数调用表达式的值返回给调用者。

In C++, the ||在 C++ 中, || operator is a short-circuit one, meaning that, if the first argument is true, it never even evaluates the second, because true || anything运算符是一个短路运算符,这意味着,如果第一个参数为真,它甚至永远不会评估第二个参数,因为true || anything true || anything is always true. true || anything都是真实的。

Hence the statement:因此声明:

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

is a short way of checking for a non-NULL function pointer and using that to decide the current return value:是一种检查非 NULL 函数指针并使用它来决定当前返回值的简短方法:

  • If the function pointer is NULL , simply return !NULL , which will give you 1 .如果函数指针为NULL ,只需返回!NULL ,它将为您提供1

  • If it's not NULL, !pb->check_fb will evaluate as 0 , so you then have to call the function, and use whatever it returns, as the return value of this function.如果它不是NULL, !pb->check_fb将评估为0 ,因此您必须调用该函数,并使用返回的任何内容作为该函数的返回值。

So it's effectively the same as:所以它实际上等同于:

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

Now I say "effectively" but the actual values returned may be slightly different between what you saw, and my final code snippet above.现在我说“有效”,但返回的实际可能与你看到的和我上面的最终代码片段略有不同。 The effect is the same however, if you're treating them as true/false values.但是,如果您将它们视为真/假值,效果是相同的。

Technically, that final line should be:从技术上讲,最后一行应该是:

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

to have exactly the same return value.具有完全相同的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM