Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bizarre use of conditional operator in Linux

Tags:

c

linux

gcc

c99

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?

like image 587
Conrad Meyer Avatar asked Oct 18 '11 22:10

Conrad Meyer


People also ask

What are the two conditional operators?

Conditional Operators The logical AND and logical OR operators both take two operands. Each operand is a boolean expression (i.e., it evaluates to either true or false). The logical AND condition returns true if both operands are true, otherwise, it returns false.

Can we use ternary operator in shell script?

Bash - Ternary Operator Bash or shell script example for Ternary Operator expression with examples. Bash programming does not have support for ternary operator syntax. The syntax is similar to if and else conditional expression. if expression is true, value1 is returned,else value2 is returned.


2 Answers

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.

like image 78
zwol Avatar answered Oct 13 '22 15:10

zwol


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.

like image 24
David Given Avatar answered Oct 13 '22 14:10

David Given