What does this mean? return func()

109 views Asked by At

In Linux kernel source code, I found this.

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? And can we return a function? Usually we return a value.

2

There are 2 answers

1
paxdiablo On BEST ANSWER

In C++, the || operator is a short-circuit one, meaning that, if the first argument is true, it never even evaluates the second, because true || anything is always true.

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:

  • If the function pointer is NULL, simply return !NULL, which will give you 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.

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.

0
Sourav Ghosh On

No, it is not returning a function itself. It is actually

  • Checking for non-NULL value of the function pointer.

    • If not NULL
      1. Calling the function using the function pointer
      2. returning the return value of the called function.
    • if NULL
      1. return !NULL (1).

Quoting C11 standard, chapter 6.8.6.4, The return statement

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.