Is this ternary conditional ?: correct (Objective) C syntax? Is this ternary conditional ?: correct (Objective) C syntax? c c

Is this ternary conditional ?: correct (Objective) C syntax?


From http://en.wikipedia.org/wiki/%3F%3A

A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:

a = x ? : y;

The expression is equivalent to

a = x ? x : y;

except that if x is an expression, it is evaluated only once. The difference is significant if evaluating the expression has side effects.


This behaviour is defined for both gcc and clang. If you're building macOS or iOS code, there's no reason not to use it.

I would not use it in portable code, though, without carefully considering it.


$ cat > foo.c#include <stdio.h>int main(int argc, char **argv){  int b = 2;  int c = 4;  int a = b ?: c;  printf("a: %d\n", a);  return 0;}$ gcc -pedantic -Wall foo.cfoo.c: In function ‘main’:foo.c:7: warning: ISO C forbids omitting the middle term of a ?: expression

So no, it's not allowed. What gcc emits in this case does this:

$ ./a.out a: 2

So the undefined behaviour is doing what you say in your question, even though you don't want to rely on that.