Conrad Meyer
Conrad Meyer

Reputation: 2897

Bizarre use of conditional operator in Linux

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 case with gcc -Wall and don't get any warnings; the behavior seems identical to:

retval = retval ? retval : desc.error;

Looking at the C99 standard, I can't figure out what formally describes this behavior. Why is this OK?

Upvotes: 37

Views: 2250

Answers (4)

zwol
zwol

Reputation: 140786

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.

Upvotes: 36

David Given
David Given

Reputation: 13701

It's a gcc extension. x ?: y is equivalent to x ? x : y --- see http://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals.

Yes, I think it's evil too.

Upvotes: 20

David Schwartz
David Schwartz

Reputation: 182827

This is a GCC extension called Conditionals with Omitted Operands. Omitting the middle operand has the effect of using the value of the conditional as the omitted operand without evaluating it again. It is safe to use even if the conditional is a macro.

Upvotes: 7

Greg Hewgill
Greg Hewgill

Reputation: 994221

This is a gcc-specific extension to C and is not standard.

Upvotes: 3

Related Questions