Bizarre use of conditional operator in Linux

后端 未结 4 1803
长发绾君心
长发绾君心 2020-12-05 23:23

In the 3.0.4 Linux kernel, mm/filemap.c has this line of code:

retval = retval ?: desc.error;

I\'ve tried compiling a similar minimal test

4条回答
  •  天涯浪人
    2020-12-05 23:26

    As several others have said, this is a GCC extension, not part of any standard. You'll get a warning for it if you use the -pedantic switch.

    The point of this extension is not really visible in this case, but imagine if instead it was

    retval = foo() ?: desc.error;
    

    With the extension, foo() is called only once. Without it, you have to introduce a temporary variable to avoid calling foo() twice.

提交回复
热议问题