1

I am currently porting some Unix code to Windows and came across a rather strange use of the conditional operator which is not valid syntax according to Visual Studio (either 2010 or 2012).

Copied and pasted without modification:

filename = filename ? : h->filename;

There is no condition! I assume it is either a check against an empty string (of the const char* sort), or against null & empty, as I can't think of anything else it can be.

Has anybody seen this before? Thank you.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
niemiro
  • 1,778
  • 1
  • 20
  • 37
  • Or http://stackoverflow.com/questions/2806255/why-would-you-use-the-ternary-operator-without-assigning-a-value-for-the-true : *"This is permitted in GNU as an obscure extension to C"* – Martin R Mar 23 '13 at 08:20
  • Thank you all for a great set of answers :) – niemiro Mar 23 '13 at 08:33

2 Answers2

2

It's a gcc extension.

x = a ? : b;

is almost the same as

x = a ? a : b;

except for the fact that a is only evaluated once, which is useful if a has any side effects or is expensive to evaluate.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
2

The given code works similar to the following code in this particular context,

if (!filename) {
    filename = h->filename;
}

Also note that in this example filename and h->filename are two different variables. filename is an ordinary variable and h->filename is the member variable of a structure.

Deepu
  • 7,592
  • 4
  • 25
  • 47